码迷,mamicode.com
首页 > 数据库 > 详细

使用JDBC的批处理功能

时间:2014-08-30 17:40:59      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   使用   io   java   ar   

bubuko.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

 

使用JDBC的批处理功能

标签:style   blog   http   color   os   使用   io   java   ar   

原文地址:http://www.cnblogs.com/aineko/p/3946520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!