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);
}
}