cs122b-2017-winter: BatchInsert.java

File BatchInsert.java, 1.8 KB (added by chenli, 21 months ago)
Line 
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.PreparedStatement;
4import java.sql.Statement;
5import java.sql.SQLException;
6
7/*
8
9The SQL command to create the table ft.
10
11DROP TABLE IF EXISTS ft;
12CREATE TABLE ft (
13    entryID INT AUTO_INCREMENT,
14    entry text,
15    PRIMARY KEY (entryID),
16    FULLTEXT (entry)) ENGINE=MyISAM;
17
18*/
19
20/*
21
22Note: Please change the username, password and the name of the datbase.
23
24*/
25
26public class BatchInsert {
27
28    public static void main (String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
29
30        Connection conn = null;
31
32        Class.forName("com.mysql.jdbc.Driver").newInstance();
33        String jdbcURL="jdbc:mysql://localhost:3306/<DB NAME>";
34
35        try {
36            conn = DriverManager.getConnection(jdbcURL,"<PUT USER NAME HERE>", "<PUT PASSWORD HERE>");
37        } catch (SQLException e) {
38            e.printStackTrace();
39        }
40
41        PreparedStatement psInsertRecord=null;
42        String sqlInsertRecord=null;
43
44        int[] iNoRows=null;
45       
46
47        sqlInsertRecord="insert into ft (entryID, entry) values(?,?)";
48        try {
49                        conn.setAutoCommit(false);
50
51            psInsertRecord=conn.prepareStatement(sqlInsertRecord);
52
53
54            for(int i=1;i<=50;i++)
55            {
56                psInsertRecord.setInt(1, i);
57                psInsertRecord.setString(2,"My next text piece " + (i*i));
58                psInsertRecord.addBatch();
59            }
60
61                        iNoRows=psInsertRecord.executeBatch();
62                        conn.commit();
63
64        } catch (SQLException e) {
65            e.printStackTrace();
66        }
67
68        try {
69            if(psInsertRecord!=null) psInsertRecord.close();
70            if(conn!=null) conn.close();
71        } catch(Exception e) {
72            e.printStackTrace();
73        }
74    }
75
76}
77
78