1.java中遍历Map使用PreparedStatement实现批量添加
Connection con = null;
PreparedStatement pstm = null;
try {
// 1. 建立与数据库的连接
con = JDBCConAndClo.getConnectionBao();
// 2. 执行sql语句
// 1).先创建PreparedStatement语句(发送slq请求):
pstm = con.prepareStatement("update T_TABLE set name = ? , alias = ? where id = ? ");
con.setAutoCommit(false);//1,首先把Auto commit设置为false,不让它自动提交
// 2) 因为参数的特殊性(三个参数有两个是相同的所以)使用map统一处理参数。
Map<String,String> map = new HashMap<String,String>();
map.put(123,"wangmett");
map.put(124,"wangmehh");
map.put(125,"wangmegg");
// 3) 将一组参数添加到此 PreparedStatement 对象的批处理命令中。
for(Map.Entry<String,String> entry: map.entrySet()){
pstm.setString(1,entry.getValue());
pstm.setString(2,entry.getValue());
pstm.setString(3,entry.getKey());
pstm.addBatch();
}
// 4) 将一批参数提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组。
pstm.executeBatch();
System.out.println("插入成功!");
// 若成功执行完所有的插入操作,则正常结束
con.commit();//2,进行手动提交(commit)
System.out.println("提交成功!");
con.setAutoCommit(true);//3,提交完成后回复现场将Auto commit,还原为true,
} catch (SQLException e) {
e.printStackTrace();
try {
// 若出现异常,对数据库中所有已完成的操作全部撤销,则回滚到事务开始状态
if(!con.isClosed()){
con.rollback();//4,当异常发生执行catch中SQLException时,记得要rollback(回滚);
System.out.println("插入失败,回滚!");
con.setAutoCommit(true);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
JDBCConAndClo.closePreparedStatement(pstm);
JDBCConAndClo.closeConnection(con);
}
}
}