package cn.flybird.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /**表 * DROP TABLE IF EXISTS `test2`; * CREATE TABLE `test2` * (`name` varchar(500)CHARACTER SET gbk DEFAULT NULL * ) * ENGINE=MyISAM DEFAULT CHARSET=gbk; * * @author Administrator * */ public class Test2 { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection con = (Connection) DriverManager.getConnection( "jdbc:mysql://" + "localhost:3306/test?characterEncoding=GBK", "root", "root"); // 關閉事務自動提交 con.setAutoCommit(false); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS"); TimeZone t = sdf.getTimeZone(); t.setRawOffset(0); sdf.setTimeZone(t); Long startTime = System.currentTimeMillis(); PreparedStatement pst = (PreparedStatement) con .prepareStatement("insert into test2 values (?)");// 對隨便1個字段操做表! int bufferSize = 0; // 對數據庫的一個表插1億條數據 for (int i = 1; i <= 100000000; i++) { bufferSize++; pst.setString(1, "插入第" + i + "條數據");// pst.addBatch(); // 每1w條數據批量處理一次提交到數據庫 if ((bufferSize + 1) % 1000 == 0) { pst.executeBatch(); con.commit(); pst.clearBatch();// 批量清除一下! } // System.out.println("第("+i+")條"); } int[] result1 = pst.executeBatch();//批量執行,若是不批量執行到必定數據時會有可能會報錯 con.commit(); System.out.println("Length:" + result1.length); // 語句執行完畢,提交本事務 Long endTime = System.currentTimeMillis(); System.out.println("用時:" + sdf.format(new Date(endTime - startTime))); pst.close(); con.close(); } } import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.Date; public class Test2 { /** * 節日短信 1 * 生活短信 2 * 詩歌短信3 * 校園短信 4 * 幸福短信 5 * 幽默短信 6 */ public static void main(String[] args) throws Exception { String path = "D:/SMS/xydx.txt"; int typeId = 1; String content = ""; Connection conn = DBHelper.getConnection(); // 關閉事務自動提交 conn.setAutoCommit(false); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); PreparedStatement pst = conn.prepareStatement("insert into sms(Id,content,createTime,typeId) values (?,?,?,?)"); int bufferSize = 0; FileReader read = null; BufferedReader reader = null; read = new FileReader(new File(path)); reader = new BufferedReader(read); content = reader.readLine(); while (content != null) { bufferSize++; pst.setInt(1, 0); pst.setString(2, content); pst.setString(3, format.format(new Date()));// pst.setInt(4, typeId); pst.addBatch(); if ((bufferSize + 1) % 1000 == 0) { pst.executeBatch(); conn.commit(); pst.clearBatch();// 批量清除一下! } content = reader.readLine(); } int[] result = pst.executeBatch();// 批量執行,若是不批量執行到必定數據時會有可能會報錯 conn.commit(); //System.out.println("Length:" + result.length); System.err.println("成功"); // 語句執行完畢,提交本事務 DBHelper.close(null, pst, conn); } }