java 批量添加、批量更新 操作数据库
(1)三种插入操作的方法
1.1 利用for循环的批量插入
示例xml
<insert id="insertUser">
insert into test_user (u_name,create_date) value (#{userName},SYSDATE())
</insert>
示例代码:
for (int i = 1; i <= num; i++) {
User user = new User();
user.setUserName("a" + i);
user.setCreateDate(new Date());
userDao.insertUser(user);
}
1.2 采用jdbc
示例代码:
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.0.200:3306/xxx", "root", "root");
conn.setAutoCommit(false);
String sql = "insert into test_user (u_name,create_date) value (?,SYSDATE())";
PreparedStatement prest = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
conn.setAutoCommit(false);
for (int i = 1; i <= 100; i++) {
prest.setString(1, "a" + i);
prest.addBatch();
}
prest.executeBatch();
conn.commit();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
1.3 采用mybatis的批量插入方法
其实也是根据一个list 拼接成一个sql
示例xml
<insert id="batchInsertList">
insert into test_user(u_name,create_date)
values
<foreach item="item" index="index" collection="userList" separator=",">
(#{item.userName},SYSDATE())
</foreach>
</insert>
示例代码
List<User> userList = new ArrayList<User>();
for (int i = 1; i <= num; i++) {
User user = new User();
user.setUserName("a" + i);
user.setCreateDate(new Date());
userList.add(user);
}
userDao.batchInsertList(userList);
(2)三种批量更新的方法
2.1 利用for循环批量更新
示例xml
<update id="updateUser">
update test_user set test_user.u_name = (#{updateUserName}) where test_user.u_name = (#{userName})
</update>
示例代码
for (int i = 1; i <= num; i++) {
User user = new User();
user.setUserName("a" + i);
user.setUpdateUserName("b" + i);
userDao.updateUser(user);
}
2.2 jdbc 批量更新
示例代码
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.0.200:3306/xxx", "root", "root");
conn.setAutoCommit(false);
// 保存当前自动提交模式
boolean autoCommit = conn.getAutoCommit();
// 关闭自动提交
conn.setAutoCommit(false);
Statement stmt =conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
for (int i = 1; i <= num; i++) {
stmt.addBatch("update test_user set test_user.u_name = ('d"+i+"') where test_user.u_name = ('c"+i+"')");
}
stmt.executeBatch();
conn.commit();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
2.3 mybatis 批量更新
其实是利用了mysql的批量更新的语法
case when的语法
详见 【case when 语法】
示例xml
<update id="batchUpdateList">
update test_user
<trim prefix="set" suffixOverrides=",">
<trim prefix="u_name =case" suffix="end,">
<foreach item="item" collection="userList">
when test_user.u_name = (#{item.userName})
then #{item.updateUserName}
</foreach>
</trim>
</trim>
where
<foreach item="item" collection="userList" separator="or">
(test_user.u_name = (#{item.userName}))
</foreach>
</update>
示例代码
for (int i = 1; i <= num; i++) {
User user = new User();
user.setUserName("a" + i);
user.setUpdateUserName("b" + i);
userList.add(user);
}
userDao.batchUpdateList(userList);