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(查询 ...
随机推荐
- es6异步编程
https://blog.csdn.net/tcy83/article/details/80274772 等一系列文章
- python爬虫学习笔记
爬虫的分类 1.通用爬虫:通用爬虫是搜索引擎(Baidu.Google.Yahoo等)“抓取系统”的重要组成部分.主要目的是将互联网上的网页下载到本地,形成一个互联网内容的镜像备份. 简单来讲就是尽可 ...
- python类的两种创建方式
参考: https://blog.csdn.net/likunkun__/article/details/81949479
- Druid.jar包
首先了解一下,什么是Druid. Druid是Java语言中最好的数据库连接池,它能够提供强大的监控和扩展功能. Druid是一个JDBC组件,它包括三部分: 1)DruidDriver 代理Driv ...
- seq2seq
seq2seq: seq2seq就是将输入序列经过encoder-decoder变成目标序列. 如图所示,输入序列是 [A, B, C, <EOS>],输出序列是 [W, X, Y, Z ...
- Python——各类库的安装(持续更新)
一.BeautifulSoup 说明:www.crummy.com:Beautiful Soup 3只能在python2.x版本中运行,而Beautiful Soup 4还可以在python3.x版本 ...
- 整理一些vue elementui 问题 + 链接方法
1.前端通过spark-md5.js计算本地文件md5 2.vue如何利用自定义的事件,在子组件中修改父组件里边的值 3.vue子组件获取父组件的内容(props属性) 4.Element ui se ...
- NIPS2017-The neural hawks process
NIPS2017哪些论文值得关注 论文链接 1.首先这篇文章研究的是 event stream,什么是event stream呢 ? 假如你是一个医生,你每天会看到很多病人 ,对于每一个病人,你都有他 ...
- P1972 [SDOI2009]HH的项链
洛谷的分块练习题 看到讨论中说分块莫队被卡就写了树状数组...(但感觉做法和莫队的思想有点像?) #include<bits/stdc++.h> using namespace std; ...
- Now you can provide attr "wx:key" for a "wx:for" to improve performance. 微信小程序警告
Now you can provide attr "wx:key" for a "wx:for" to improve performance为警告,不处理不影 ...