码迷,mamicode.com
首页 > 其他好文 > 详细

Using QueryRunner to insert ArrayList<Object[]>

时间:2017-11-01 16:28:52      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:连接数据库   cts   cond   UI   tom   技术分享   else   mes   mysq   

使用QueryRunner 结合c3p0进行数据库操作时候,

需求:list<bean>进行插入数据库中,但是QueryRunner 仅仅支持batch():批处理;

 

Object[][] params = null;

 

qr.batch("insert into MyTable (param1,param2,param3) values (?,?,?)", params);

需要把后面的参数设置成二维数组,但是如何设置成这种二维数组呢,下面提供类
ModelToSqlConverter.java
技术分享
package com.htzq.dbutil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ModelToSqlConverter {

    private Object model;

    private List<Object> params, keyParams, modelList;

    private String fieldNameString, questionMarkString, sqlString, conditionString, updateString;

    private boolean update;

    private String[] keys;

    private Object[][] multiParams;

    /**
     * Initializes a newly created <code>ModelToSqlConverter</code>
     *
     * @param model The model representing the ASW file.
     * @param keys The keys for locating the right row in ASW file.
     */
    @SuppressWarnings("unchecked")
    public ModelToSqlConverter(Object model, String... keys){
        this.model = model;
        this.keys = keys;
        params = new ArrayList<Object>();
        keyParams = new ArrayList<Object>();
        questionMarkString = "VALUES (";
        fieldNameString = "(";
        updateString = "";
        conditionString = "WHERE ";
        update = keys != null && keys.length > 0;
        if(model instanceof List<?>){
            modelList = (List<Object>) model;
            convertModelListToSqlAndParams();
        }else{
            convertModelToSqlAndParams();
        }

    }

    /**
     * Main method for Converting Model into SQL String and to value parameters.
     */
    private void convertModelToSqlAndParams(){

        for(Field field : model.getClass().getDeclaredFields()){
            try{
                field.setAccessible(true);
                Object value = field.get(model);
                String fieldName = field.getName();
                if(value != null && !fieldName.equalsIgnoreCase("serialVersionUID")){
                    if(!update){
                        addQuestionMark();
                        addNameToSql(fieldName);
                        addValueToObjectArray(value);
                    }else{
                        if(isKey(fieldName)){
                            conditionString += fieldName + " = ?,";
                            keyParams.add(value);

                        }else{
                            addParamAndNameToSql(fieldName);
                            addValueToObjectArray(value);
                        }
                    }
                }

            }catch(IllegalArgumentException e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch(IllegalAccessException e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        sqlString = update ? getUpdateSql() : getInsertSql();
        for(Object key : keyParams){
            addValueToObjectArray(key);
        }
    }

    /**
     * Main method for Converting Model into SQL String and to value parameters.
     */
    private void convertModelListToSqlAndParams(){
        int row = 0;
        boolean isKey = false;
        boolean firstModel = true;
        Field[] fields = modelList.get(0).getClass().getDeclaredFields();
        multiParams = new Object[modelList.size()][fields.length];
        for(Object model : modelList){
            int col = 0;
            keyParams = new ArrayList<Object>();
            for(Field field : fields){
                try{
                    field.setAccessible(true);
                    Object value = field.get(model);
                    String fieldName = field.getName();
                    if(value != null && !fieldName.equalsIgnoreCase("serialVersionUID")){
                        if(!update){
                            if(firstModel){
                                addQuestionMark();
                                addNameToSql(fieldName);
                            }
                            addValueToMultiParams(value, row, col);
                        }else{
                            isKey = isKey(fieldName);
                            if(isKey){
                                if(firstModel){
                                    conditionString += fieldName + " = ?,";
                                }
                                keyParams.add(value);
                            }else{
                                if(firstModel)
                                    addParamAndNameToSql(fieldName);
                                addValueToMultiParams(value, row, col);
                            }
                        }
                    }

                }catch(IllegalArgumentException e){
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }catch(IllegalAccessException e){
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if(!isKey)
                    col++;
            }
            firstModel = false;
            for(Object key : keyParams){
                addValueToMultiParams(key, row, col);
                col++;
            }
            row++;
        }
        sqlString = update ? getUpdateSql() : getInsertSql();

    }

    /**
     * @param columnName
     */
    private void addNameToSql(String columnName){
        fieldNameString += columnName + ",";
    }

    /**
     * @param value
     */
    private void addValueToObjectArray(Object value){
        params.add(value);
    }

    /**
     * @param value
     * @param row
     * @param col
     */
    private void addValueToMultiParams(Object value, int row, int col){
        multiParams[row][col] = value;
    }

    public Object[][] getMultiValueParams(){
        return removeNullsFromMultiArray(multiParams);
    }

    /**
     * Adds question mark to string
     */
    private void addQuestionMark(){
        questionMarkString += "?,";
    }

    /**
     * @param columnName
     */
    private void addParamAndNameToSql(String columnName){
        updateString += columnName + "= ?,";
    }

    /**
     * @return the update SQL string.
     */
    private String getUpdateSql(){
        return updateString.substring(0, updateString.lastIndexOf(",")) + " " + conditionString.substring(0, conditionString.lastIndexOf(","));
    }

    /**
     * @return the insert SQL string.
     */
    private String getInsertSql(){
        return fieldNameString.substring(0, fieldNameString.lastIndexOf(",")) + ") " + questionMarkString.substring(0, questionMarkString.lastIndexOf(","))
                + ")";
    }

    private Object[][] removeNullsFromMultiArray(Object[][] multiValuedArray){
        for(int i = 0; i < multiValuedArray.length; i++){
            ArrayList<Object> list = new ArrayList<Object>(); // creates a list to store the elements !=
                                                                // null
            for(int j = 0; j < multiValuedArray[i].length; j++){
                if(multiValuedArray[i][j] != null){
                    list.add(multiValuedArray[i][j]); // elements != null will be added to the list.
                }
            }
            multiValuedArray[i] = list.toArray(new Object[list.size()]); // all elements from list to an
                                                                            // array.
        }
        return multiValuedArray;
    }

    /**
     * Checks if the field name is a key.
     * 
     * @param fieldName
     * @return true if the field is a key.
     */
    private boolean isKey(String fieldName){
        boolean isKey = false;
        for(String key : keys){
            if(fieldName.equalsIgnoreCase(key)){
                isKey = true;
            }
        }
        return isKey;
    }

    /**
     * @return the params
     */
    public Object[] getParams(){
        return params.toArray();
    }

    /**
     * @return the sqlString
     */
    public String getSqlString(){
        return sqlString;
    }

    /**
     * @param params the params to set
     */
    public void setParams(List<Object> params){
        this.params = params;
    }

    /**
     * @param sqlString the sqlString to set
     */
    public void setSqlString(String sqlString){
        this.sqlString = sqlString;
    }
}
View Code

C3P0MySqlConnection.java

 1 package com.htzq.dbutil;
 2 
 3 import java.beans.PropertyVetoException;
 4 import java.sql.SQLException;
 5 
 6 import com.mchange.v2.c3p0.ComboPooledDataSource;
 7 
 8 public class C3P0MySqlConnection {
 9 
10     public ComboPooledDataSource C3P0SqlServerConnection(String []a) throws SQLException {
11          ComboPooledDataSource ds = new ComboPooledDataSource() ;
12         try {
13             ds = new ComboPooledDataSource();//创建连接池实例  
14             ds.setDriverClass("com.mysql.jdbc.Driver");//设置连接池连接数据库所需的驱动  
15              ds.setJdbcUrl(a[0]);//设置连接数据库的URL  
16              ds.setUser(a[1]);//设置连接数据库的用户名  
17              ds.setPassword(a[2]);//设置连接数据库的密码  
18              ds.setMaxPoolSize(40);//设置连接池的最大连接数  
19              ds.setMinPoolSize(2);//设置连接池的最小连接数  
20              ds.setInitialPoolSize(5);//设置连接池的初始连接数  
21              ds.setMaxStatements(100);//设置连接池的缓存Statement的最大数         
22         } catch (PropertyVetoException e) {
23             // TODO Auto-generated catch block
24             e.printStackTrace();
25         }
26         return ds;
27     
28     }
29 }

逻辑处理

1         String sql = sqlBuf.substring(0, sqlBuf.length()-10);
2             List<ShWtqr> list = iSysConfigDao.selectSysCollect(a ,sql);
3             
4             a = readPropertiesUtil.readMySqlPro();
5             ModelToSqlConverter modelToSqlConverter = new ModelToSqlConverter(list);
6             String mysql = "INSERT INTO " + list.get(0).getClass().getSimpleName().toUpperCase() + " " + modelToSqlConverter.getSqlString();
7             
8             int v = iSysConfigDao.insertSysCollect(a ,mysql,modelToSqlConverter.getMultiValueParams());
insertSysCollect函数如下

 1     @Override
 2     public int insertSysCollect(String[] a,String sql, Object[][] c) {
 3         List<ShWtqr> list = null;
 4         try {
 5             C3P0MySqlConnection c3p0MySqlConnection = new C3P0MySqlConnection();
 6             ComboPooledDataSource ds  = c3p0MySqlConnection.C3P0SqlServerConnection(a);
 7             
 8             QueryRunner queryRunner = new QueryRunner(ds);
 9             int []b = queryRunner.batch(sql, c);
10         } catch (SQLException e) {
11             // TODO Auto-generated catch block
12             e.printStackTrace();
13         }
14         return 0;
15     }

 








Using QueryRunner to insert ArrayList<Object[]>

标签:连接数据库   cts   cond   UI   tom   技术分享   else   mes   mysq   

原文地址:http://www.cnblogs.com/wang3680/p/7766927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!