你向 MySQL 數(shù)據(jù)庫插入 100w 條數(shù)據(jù)用了多久?
閱讀本文大概需要 2.8 分鐘。
來源 | http://juejin.im/post/5d255ab9e51d454f73356dcd
多線程插入(單表)
鏈接耗時 (30%) 發(fā)送query到服務(wù)器 (20%) 解析query (20%) 插入操作 (10% * 詞條數(shù)目) 插入index (10% * Index的數(shù)目) 關(guān)閉鏈接 (10%)
多線程插入(多表)
預(yù)處理SQL
普通SQL,即使用Statement接口執(zhí)行SQL 預(yù)處理SQL,即使用PreparedStatement接口執(zhí)行SQL
String sql = "insert into testdb.tuser (name, remark, createtime, updatetime) values (?, ?, ?, ?)";
for (int i = 0; i < m; i++) {
//從池中獲取連接
Connection conn = myBroker.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int k = 0; k < n; k++) {
pstmt.setString(1, RandomToolkit.generateString(12));
pstmt.setString(2, RandomToolkit.generateString(24));
pstmt.setDate(3, new Date(System.currentTimeMillis()));
pstmt.setDate(4, new Date(System.currentTimeMillis()));
//加入批處理
pstmt.addBatch();
}
pstmt.executeBatch(); //執(zhí)行批處理
pstmt.close();
myBroker.freeConnection(conn); //連接歸池
}
多值插入SQL
普通插入SQL:INSERT INTO TBL_TEST (id) VALUES(1) 多值插入SQL:INSERT INTO TBL_TEST (id) VALUES (1), (2), (3)
事務(wù)(N條提交一次)
/// <summary>
/// 執(zhí)行多條SQL語句,實現(xiàn)數(shù)據(jù)庫事務(wù)。
/// </summary>mysql數(shù)據(jù)庫
/// <param name="SQLStringList">多條SQL語句</param>
public void ExecuteSqlTran(List<string> SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
if (DBVariable.flag)
{
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
MySqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
//后來加上的
if (n > 0 && (n % 1000 == 0 || n == SQLStringList.Count - 1))
{
tx.Commit();
tx = conn.BeginTransaction();
}
}
//tx.Commit();//原來一次性提交
}
catch (System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
}
10w條數(shù)據(jù)大概用時10s!
