Using QueryRunner to insert ArrayList<Object[]>
使用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;
}
}
C3P0MySqlConnection.java
package com.htzq.dbutil; import java.beans.PropertyVetoException;
import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0MySqlConnection { public ComboPooledDataSource C3P0SqlServerConnection(String []a) throws SQLException {
ComboPooledDataSource ds = new ComboPooledDataSource() ;
try {
ds = new ComboPooledDataSource();//创建连接池实例
ds.setDriverClass("com.mysql.jdbc.Driver");//设置连接池连接数据库所需的驱动
ds.setJdbcUrl(a[0]);//设置连接数据库的URL
ds.setUser(a[1]);//设置连接数据库的用户名
ds.setPassword(a[2]);//设置连接数据库的密码
ds.setMaxPoolSize(40);//设置连接池的最大连接数
ds.setMinPoolSize(2);//设置连接池的最小连接数
ds.setInitialPoolSize(5);//设置连接池的初始连接数
ds.setMaxStatements(100);//设置连接池的缓存Statement的最大数
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ds; }
}
逻辑处理
String sql = sqlBuf.substring(0, sqlBuf.length()-10);
List<ShWtqr> list = iSysConfigDao.selectSysCollect(a ,sql); a = readPropertiesUtil.readMySqlPro();
ModelToSqlConverter modelToSqlConverter = new ModelToSqlConverter(list);
String mysql = "INSERT INTO " + list.get(0).getClass().getSimpleName().toUpperCase() + " " + modelToSqlConverter.getSqlString(); int v = iSysConfigDao.insertSysCollect(a ,mysql,modelToSqlConverter.getMultiValueParams());
insertSysCollect函数如下
@Override
public int insertSysCollect(String[] a,String sql, Object[][] c) {
List<ShWtqr> list = null;
try {
C3P0MySqlConnection c3p0MySqlConnection = new C3P0MySqlConnection();
ComboPooledDataSource ds = c3p0MySqlConnection.C3P0SqlServerConnection(a); QueryRunner queryRunner = new QueryRunner(ds);
int []b = queryRunner.batch(sql, c);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
Using QueryRunner to insert ArrayList<Object[]>的更多相关文章
- Intent.putExtra()传递Object对象或者ArrayList<Object> (转)
Intent传递基本类型相信大家都十分熟悉,如何传递Object对象或者ArrayList<Object>对象呢? 可以通过: (1)public Intent putExtra (Str ...
- Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
报错: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlace ...
- * -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]’
错误描述: * -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object fr ...
- [原创]JAVA技巧:去除ArrayList<Object>里面的重复记录
简单说明 ArrayList中保存的是某种类型的对象,如User,现在需要将对象属性userid重复的都去掉,使userid唯一,要如何处理? 实现步骤 代码如下方所示,实现一个Comparator的 ...
- iOS项目运行出现:[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object
说白了就是 字典初始化 的时候 放入空的值了 下面这个比较具体 错误原因: NSDictionary *dic = @{@"key":value}这个初始化方法,发现keys co ...
- List<List<Object>> list = new ArrayList<List<Object>>(); 求回答补充问题 list.get(position).add(Object);为什么会报错啊我想在对应的list里面添加对象
public static void main(String[] args){ List<List<Object>> list = new ArrayList<List& ...
- 执行ArrayList的remove(object)方法抛异常?
简介 或许有很多小伙伴都尝试过如下的代码: ArrayList<Object> list = ...; for (Object object : list) { if (条件成立) { l ...
- 使用ThreadLocal、Apache的dbutils的QueryRunner和dbcp2数据库连接池的BasicDataSource封装操作数据库工具
package hjp.smart4j.framework.helper; import hjp.smart4j.framework.util.CollectionUtil; import hjp.s ...
- c3p0和QueryRunner的结合使用,让开发更加简便
1:DBUtils中的QueryRunner的使用: 1.1:QueryRunner中提供了对SQL语句操作的api: 1.2:主要有三个方法: 1.2.1:query():用于执行select(查询 ...
随机推荐
- 1068: [SCOI2007]压缩
题解: 区间DP 考虑状态的设计: \(dp[i][j][0/1]\)表示原字符串的\(i-j\)区间有无在中间加\(M\).并且默认在\(i\)之前加入\(M\)压缩后的最小长度,显然有转移: \[ ...
- EC20 R2.1
1.模块开机成功前WAKEUP_IN. NET_MODE. BT_CTS. COEX_UART_TX(背部焊盘). COEX_UART_RX(背部焊盘) 和WLAN_EN(背部焊盘)引脚禁止上拉. 2 ...
- WebDriver下载地址
http://chromedriver.storage.googleapis.com/index.html https://blog.csdn.net/ccggaag/article/details/ ...
- flask 出现 TemplateNotFound的问题
from flask import Flask, render_template, request app = Flask(__name__,template_folder='./templates' ...
- 一个关于kindle固件修改的问题
手头有一个序列号为B05A开头的日版kpw2,默认没有中文界面.之前看过@5201992318q 大神的帖子,原因是系统langpicker.conf文件中有一段判断序列号并删除语言的代码,于是我萌发 ...
- 堆应用---构造Huffman树(C++实现)
堆: 堆是STL中priority_queue的最高效的实现方式(关于priority_queue的用法:http://www.cnblogs.com/flyoung2008/articles/213 ...
- day 25-1 接口类、抽象类、多态
# 接口类:python 原生不支持# 抽象类:python 原生支持的 接口类 首先我们来看一个支付接口的简单例子 from abc import abstractmethod,ABCMeta #我 ...
- Spring框架中的org.springframework.context.annotation.Import注解类
@Import注解的作用和在使用spring的xml配置时用到的<import/>类似.但应注意是@Import在使用时必须要保证能被IOC容器扫描到,所以通常它会和@Configurat ...
- patindex
功能:返回模式在字符串中第一次出现的位置 解释:patindex('%pattern%',expression) pattern:要查找的模式 expression:被找的字符串 例子:select ...
- Python——IPython和NumPy
IPython: 一个增强的Python shell:许多python对象的显示形式更友好.更详细的异常显示.增加额外的命令交互式数据处理 Tab键自动完成: 键入一些内容之后,按Tab键,显示可能的 ...