Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.apache.storm.jdbc.common;
 
 
 import java.sql.*;
 import java.sql.Date;
 import java.util.*;
 
 public class JdbcClient {
     private static final Logger LOG = LoggerFactory.getLogger(JdbcClient.class);
 
     private int queryTimeoutSecs;
 
     public JdbcClient(ConnectionProvider connectionProviderint queryTimeoutSecs) {
         this. = connectionProvider;
         this. = queryTimeoutSecs;
     }
 
     public void insert(String tableNameList<List<Column>> columnLists) {
         String query = constructInsertQuery(tableNamecolumnLists);
         executeInsertQuery(querycolumnLists);
     }
 
     public void executeInsertQuery(String queryList<List<Column>> columnLists) {
         Connection connection = null;
         try {
             connection = .getConnection();
             boolean autoCommit = connection.getAutoCommit();
             if(autoCommit) {
                 connection.setAutoCommit(false);
             }
 
             .debug("Executing query {}"query);
 
             PreparedStatement preparedStatement = connection.prepareStatement(query);
             if( > 0) {
                 preparedStatement.setQueryTimeout();
             }
 
             for(List<ColumncolumnList : columnLists) {
                 setPreparedStatementParams(preparedStatementcolumnList);
                 preparedStatement.addBatch();
             }
 
             int[] results = preparedStatement.executeBatch();
             if(Arrays.asList(results).contains(.)) {
                 connection.rollback();
                 throw new RuntimeException("failed at least one sql statement in the batch, operation rolled back.");
             } else {
                 try {
                     connection.commit();
                 } catch (SQLException e) {
                     throw new RuntimeException("Failed to commit insert query " + querye);
                 }
             }
         } catch (SQLException e) {
             throw new RuntimeException("Failed to execute insert query " + querye);
         } finally {
             closeConnection(connection);
         }
     }
 
     private String constructInsertQuery(String tableNameList<List<Column>> columnLists) {
         StringBuilder sb = new StringBuilder();
         sb.append("Insert into ").append(tableName).append(" (");
         Collection<StringcolumnNames = Collections2.transform(columnLists.get(0), new Function<ColumnString>() {
             @Override
             public String apply(Column input) {
                 return input.getColumnName();
             }
         });
         String columns = Joiner.on(",").join(columnNames);
         sb.append(columns).append(") values ( ");
 
         String placeHolders = StringUtils.chop(StringUtils.repeat("?,"columnNames.size()));
        sb.append(placeHolders).append(")");
        return sb.toString();
    }
    public List<List<Column>> select(String sqlQueryList<ColumnqueryParams) {
        Connection connection = null;
        try {
            connection = .getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
            if( > 0) {
                preparedStatement.setQueryTimeout();
            }
            setPreparedStatementParams(preparedStatementqueryParams);
            ResultSet resultSet = preparedStatement.executeQuery();
            List<List<Column>> rows = Lists.newArrayList();
            while(resultSet.next()){
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();
                List<Columnrow = Lists.newArrayList();
                for(int i=1 ; i <= columnCounti++) {
                    String columnLabel = metaData.getColumnLabel(i);
                    int columnType = metaData.getColumnType(i);
                    Class columnJavaType = Util.getJavaType(columnType);
                    if (columnJavaType.equals(String.class)) {
                        row.add(new Column<String>(columnLabelresultSet.getString(columnLabel), columnType));
                    } else if (columnJavaType.equals(Integer.class)) {
                        row.add(new Column<Integer>(columnLabelresultSet.getInt(columnLabel), columnType));
                    } else if (columnJavaType.equals(Double.class)) {
                        row.add(new Column<Double>(columnLabelresultSet.getDouble(columnLabel), columnType));
                    } else if (columnJavaType.equals(Float.class)) {
                        row.add(new Column<Float>(columnLabelresultSet.getFloat(columnLabel), columnType));
                    } else if (columnJavaType.equals(Short.class)) {
                        row.add(new Column<Short>(columnLabelresultSet.getShort(columnLabel), columnType));
                    } else if (columnJavaType.equals(Boolean.class)) {
                        row.add(new Column<Boolean>(columnLabelresultSet.getBoolean(columnLabel), columnType));
                    } else if (columnJavaType.equals(byte[].class)) {
                        row.add(new Column<byte[]>(columnLabelresultSet.getBytes(columnLabel), columnType));
                    } else if (columnJavaType.equals(Long.class)) {
                        row.add(new Column<Long>(columnLabelresultSet.getLong(columnLabel), columnType));
                    } else if (columnJavaType.equals(Date.class)) {
                        row.add(new Column<Date>(columnLabelresultSet.getDate(columnLabel), columnType));
                    } else if (columnJavaType.equals(Time.class)) {
                        row.add(new Column<Time>(columnLabelresultSet.getTime(columnLabel), columnType));
                    } else if (columnJavaType.equals(Timestamp.class)) {
                        row.add(new Column<Timestamp>(columnLabelresultSet.getTimestamp(columnLabel), columnType));
                    } else {
                        throw new RuntimeException("type =  " + columnType + " for column " + columnLabel + " not supported.");
                    }
                }
                rows.add(row);
            }
            return rows;
        } catch (SQLException e) {
            throw new RuntimeException("Failed to execute select query " + sqlQuerye);
        } finally {
            closeConnection(connection);
        }
    }
    public List<ColumngetColumnSchema(String tableName) {
        Connection connection = null;
        List<Columncolumns = new ArrayList<Column>();
        try {
            connection = .getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getColumns(nullnulltableNamenull);
            while (resultSet.next()) {
                columns.add(new Column(resultSet.getString("COLUMN_NAME"), resultSet.getInt("DATA_TYPE")));
            }
            return columns;
        } catch (SQLException e) {
            throw new RuntimeException("Failed to get schema for table " + tableNamee);
        } finally {
            closeConnection(connection);
        }
    }
    public void executeSql(String sql) {
        Connection connection = null;
        try {
            connection = .getConnection();
            Statement statement = connection.createStatement();
            statement.execute(sql);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to execute SQL"e);
        } finally {
            closeConnection(connection);
        }
    }
    private void setPreparedStatementParams(PreparedStatement preparedStatementList<ColumncolumnListthrows SQLException {
        int index = 1;
        for (Column column : columnList) {
            Class columnJavaType = Util.getJavaType(column.getSqlType());
            if (column.getVal() == null) {
                preparedStatement.setNull(indexcolumn.getSqlType());
            } else if (columnJavaType.equals(String.class)) {
                preparedStatement.setString(index, (Stringcolumn.getVal());
            } else if (columnJavaType.equals(Integer.class)) {
                preparedStatement.setInt(index, (Integercolumn.getVal());
            } else if (columnJavaType.equals(Double.class)) {
                preparedStatement.setDouble(index, (Doublecolumn.getVal());
            } else if (columnJavaType.equals(Float.class)) {
                preparedStatement.setFloat(index, (Floatcolumn.getVal());
            } else if (columnJavaType.equals(Short.class)) {
                preparedStatement.setShort(index, (Shortcolumn.getVal());
            } else if (columnJavaType.equals(Boolean.class)) {
                preparedStatement.setBoolean(index, (Booleancolumn.getVal());
            } else if (columnJavaType.equals(byte[].class)) {
                preparedStatement.setBytes(index, (byte[]) column.getVal());
            } else if (columnJavaType.equals(Long.class)) {
                preparedStatement.setLong(index, (Longcolumn.getVal());
            } else if (columnJavaType.equals(Date.class)) {
                preparedStatement.setDate(index, (Datecolumn.getVal());
            } else if (columnJavaType.equals(Time.class)) {
                preparedStatement.setTime(index, (Timecolumn.getVal());
            } else if (columnJavaType.equals(Timestamp.class)) {
                preparedStatement.setTimestamp(index, (Timestampcolumn.getVal());
            } else {
                throw new RuntimeException("Unknown type of value " + column.getVal() + " for column " + column.getColumnName());
            }
            ++index;
        }
    }
    private void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("Failed to close connection"e);
            }
        }
    }
New to GrepCode? Check out our FAQ X