最深沉的黑暗,静静地潜伏在每个人的欲望之中。 ——迷宫里的生物链
Talk is cheap show me the code!
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.UUID;
public class InsertTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
final String url = "jdbc:mysql://192.168.1.99:3306/b2b2c2";
final String name = "com.mysql.jdbc.Driver";
final String user = "superadmin";
final String password = "admin123";
Connection conn = null;
Class.forName(name); //指定连接类型
conn = DriverManager.getConnection(url, user, password); //获取连接
if (conn != null) {
System.out.println("获取连接成功");
insert(conn);
} else {
System.out.println("获取连接失败");
}
}
public static void insert(Connection conn) {
// 开始时间
Long begin = System.currentTimeMillis();
// sql前缀
String prefix = "INSERT INTO `es_member`( `agentid`, `parentid`, `lv_id`, `uname`, `email`, `password`, `regtime`, `name`, `sex`, `birthday`, `advance`, `province_id`, `city_id`, `region_id`, `town_id`, `province`, `city`, `region`, `town`, `address`, `zip`, `mobile`, `tel`, `point`, `mp`, `QQ`, `msn`, `remark`, `lastlogin`, `is_agent`, `logincount`, `is_cheked`, `registerip`, `recommend_point_state`, `last_send_email`, `info_full`, `find_code`, `face`, `nickname`, `midentity`, `disabled`, `qq_id`, `wechat_id`, `weibo_id`, `store_id`, `is_store`, `wx_id`, `wx_userid`, `gold_coin`, `channel_id`, `channel_openid`) VALUES ";
try {
// 保存sql后缀
StringBuffer suffix = new StringBuffer();
// 设置事务为非自动提交
conn.setAutoCommit(false);
// 比起st,pst会更好些
PreparedStatement pst = (PreparedStatement) conn.prepareStatement("");
//准备执行语句
// 外层循环,总提交事务次数
for (int i = 1; i <= 100; i++) {
suffix = new StringBuffer();
// 第j次提交步长
for (int j = 1; j <= 100000; j++) {
// 构建SQL后缀
String uuid = UUID.randomUUID().toString();
String phone = "15412" + String.valueOf(Integer.valueOf(100000 * i) + j);
suffix.append(" ( NULL, 0, 1, '" + uuid + "', NULL, '" + uuid + "', 1541249863, 'ab7e1f2b-c4cd-47d4-9388-7e4f9b7ba38d', 1, NULL, 0.00, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '北京市', NULL, '" + phone + "', NULL, 0, 0, NULL, NULL, NULL, 1541252963, 0, 315, 0, NULL, 0, NULL, 0, NULL, 'http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epzE5XF0EtUcmjMbCJDJRVRNe5LEPPsxpT8ibnFSKcfNNuX33KPdMNW6DI94lUg2g1tvDbS1szpYRw/132', 'xiaowei', 0, 0, NULL, '{\\\"wx01b819e2c71f0974\\\":\\\"os5941GzFQ8YtrkAhd_Kaj6XAmf0\\\",\\\"wx7ad7bdfe3c6553aa\\\":\\\"oMMdo5BGusBXYLq7UIZoyaEiCzbY\\\"}', NULL, 0, 0, NULL, NULL, 0000000000, 1, ''), " );
}
// 构建完整SQL
String sql = prefix + suffix.substring(0, suffix.length() - 1);
// 添加执行SQL
pst.addBatch(sql);
// 执行操作
pst.executeBatch();
// 提交事务
conn.commit();
// 清空上一次添加的数据
suffix = new StringBuffer();
}
// 头等连接
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 结束时间
Long end = System.currentTimeMillis();
// 耗时
System.out.println("1000万条数据插入花费时间 : " + (end - begin) / 1000 + " s");
System.out.println("插入完成");
}
}