国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MySQL > 正文

使用JDBC在MySQL數據庫中如何快速批量插入數據

2024-07-24 12:53:26
字體:
來源:轉載
供稿:網友

使用JDBC連接MySQL數據庫進行數據插入的時候,特別是大批量數據連續插入(10W+),如何提高效率呢?

在JDBC編程接口中Statement 有兩個方法特別值得注意:

void addBatch() throws SQLException

Adds a set of parameters to this PreparedStatement object's batch of commands.

int[] executeBatch() throws SQLException

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts. The int elements of the array that is returned are ordered to correspond to the commands in the batch, which are ordered according to the order in which they were added to the batch.

通過使用addBatch()和executeBatch()這一對方法可以實現批量處理數據。

不過值得注意的是,首先需要在數據庫鏈接中設置手動提交,connection.setAutoCommit(false),然后在執行Statement之后執行connection.commit()。

package cyl.demo.ipsearcher; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class DbStoreHelper { private String insert_sql; private String charset; private boolean debug; private String connectStr; private String username; private String password; public DbStoreHelper() { connectStr = "jdbc:mysql://localhost:3306/db_ip"; // connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true"; insert_sql = "INSERT INTO tb_ipinfos (iplong1,iplong2,ipstr1,ipstr2,ipdesc) VALUES (?,?,?,?,?)"; charset = "gbk"; debug = true; username = "root"; password = "***"; } public void storeToDb(String srcFile) throws IOException { BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), charset)); try { doStore(bfr); } catch (Exception e) { e.printStackTrace(); } finally { bfr.close(); } } private void doStore(BufferedReader bfr) throws ClassNotFoundException, SQLException, IOException { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(connectStr, username,password); conn.setAutoCommit(false); // 設置手動提交 int count = 0; PreparedStatement psts = conn.prepareStatement(insert_sql); String line = null; while (null != (line = bfr.readLine())) { String[] infos = line.split(";"); if (infos.length < 5) continue; if (debug) { System.out.println(line); } psts.setLong(1, Long.valueOf(infos[0])); psts.setLong(2, Long.valueOf(infos[1])); psts.setString(3, infos[2]); psts.setString(4, infos[3]); psts.setString(5, infos[4]); psts.addBatch(); // 加入批量處理 count++; } psts.executeBatch(); // 執行批量處理 conn.commit(); // 提交 System.out.println("All down : " + count); conn.close(); } }
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 板桥市| 洛川县| 莒南县| 河源市| 梁河县| 怀远县| 油尖旺区| 沙田区| 永福县| 昌吉市| 无为县| 临清市| 沂水县| 浦江县| 宁波市| 新乡市| 扎鲁特旗| 类乌齐县| 衡水市| 长葛市| 瑞丽市| 大石桥市| 彰化市| 固镇县| 望城县| 岢岚县| 临洮县| 柳江县| 上高县| 含山县| 浑源县| 龙口市| 墨脱县| 嵩明县| 西峡县| 五台县| 四川省| 玉环县| 富顺县| 丽江市| 简阳市|