您的位置:首页 > 博客中心 > 数据库 >

使用JDBC的批处理功能

时间:2022-03-13 23:12

gxlsystem.com,布布扣gxlsystem.com,布布扣

 1 package cn.itcast.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.Date;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 import java.sql.Statement;
 9 
10 public class BatchTest {
11 
12     public static void main(String[] args) throws SQLException {
13         /*for (int i = 0; i < 1000; i++) {
14             create(i);
15         }*/
16         createBatch();
17     }
18 
19     static int create(int i) throws SQLException {
20         Connection conn = null;
21         PreparedStatement ps = null;
22         ResultSet rs = null;
23 
24         try {
25             conn = jdbcUtils.getConnection();
26 
27             String sql = "insert into user(name,birthday,money) values(?,?,?)";
28 
29             ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
30             ps.setString(1, "name" + i);
31             ps.setDate(2, (java.sql.Date) new Date(System.currentTimeMillis()));
32             ps.setFloat(3, 1000F + i);
33 
34             ps.executeUpdate();
35 
36             rs = ps.getGeneratedKeys();
37             int id = 0;
38 
39             if (rs.next())
40                 id = rs.getInt(1);
41 
42             return id;
43 
44         } finally {
45             jdbcUtils.free(rs, ps, conn);
46         }
47     }
48 
49     static void createBatch() throws SQLException {
50         Connection conn = null;
51         PreparedStatement ps = null;
52         ResultSet rs = null;
53 
54         try {
55             conn = jdbcUtils.getConnection();
56 
57             String sql = "insert into user(name,birthday,money) values(?,?,?)";
58 
59             ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
60 
61             for (int i = 0; i < 1000; i++) {
62                 ps.setString(1, "name" + i);
63                 ps.setDate(2, new Date(System.currentTimeMillis()));
64                 ps.setFloat(3, 1000F + i);
65 
66                 ps.addBatch();
67             }
68 
69             int[] is = ps.executeBatch();
70 
71         } finally {
72             jdbcUtils.free(rs, ps, conn);
73         }
74     }
75 
76 }
BatchTest

 

热门排行

今日推荐

热门手游