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(查询 ...
随机推荐
- “三次握手,四次挥手”你真的懂吗?TCP
“三次握手,四次挥手”你真的懂吗? mp.weixin.qq.com 来源:码农桃花源 解读:“拼多多”被薅的问题出在哪儿?损失将如何买单? 之前有推过一篇不错的干货<TCP之三次握手四次挥手 ...
- 构建一个maven聚合类型的横向可扩展项目
那个时候初入java这个大家庭,学习的方向很乱.毕业后,在公司磨练了一年,总想着是该交一份答卷了,可能成绩不会很好,但求及格!那么考试题目呢,我计划搭建一个横向可扩展的项目,可以在平台自扩展各种子项目 ...
- 夜神模拟器调试web APP
前言:之前工作之余的时间自己做了一个web APP,但是都是在浏览器上调试的,这次想看看在手机上啥效果,所以下载了一个夜神模拟器 一.下载夜神模拟器 https://www.yeshen.com/ 二 ...
- 20175209 实验二《Java面向对象程序设计》实验报告
20175209 实验二<Java面向对象程序设计>实验报告 一.实验前期准备 了解三种代码 伪代码 产品代码 测试代码 我们先写伪代码,伪代码 从意图层面来解决问题: 有了伪代码 我们用 ...
- CMakeList.txt(1):cmake error
cmake_symlink_library: System Error: Operation not supported 1/创建链接不成功,要确认当前帐户下是否有权限在编译的目录中有创建链接的权限 ...
- Mac 设计师必备的设计绘图软件 推荐与下载
Mac设计师必备的设计绘图软件,为广大设计师推荐一些Mac上实用且强大的软件,使用好的软件,事半功倍,设计出精美的作品. Mac上优秀的设计类软件非常多,绝对不止这几款软件,看看以下内容,希望对你有帮 ...
- CDN-常用静态资源公共库
js.css 等静态资源可以放在自己的服务器上,或者引用网络上的公共库使用(CDN) CDN 读取失败时从本地加载 <script src="https://code.jquery.c ...
- JAVA进阶21
1.Vector向量 如何选用ArrayList.LinkedList.Vector? ①需要线程安全时,用Vector ②不存在线程安全问题时,并且查找较多用ArrayList(一般使用它) ③不存 ...
- Deep Mutual Learning
论文地址: https://arxiv.org/abs/1706.00384 论文简介 该论文探讨了一种与模型蒸馏(model distillation)相关却不同的模型---即相互学习(mutual ...
- Linux kill 命令 以及USR1 信号解释
kill 中的USR信号解释 USR1亦通常被用来告知应用程序重载配置文件:例如,向Apache HTTP服务器发送一个USR1信号将导致以下步骤的发生:停止接受新的连接,等待当前连接停止,重新载入配 ...