一次执行1700条插入语句,发现耗时需要20多秒,太慢了。
百度后发现只要加入事务就可以大大提高执行速度。
代码如下,速度提高到180毫秒
public static void BulkInsert(string sqlStr)
{
Stopwatch sw = new Stopwatch();
sw.Start();
{
using (IDbConnection conn = DapperHelper.MySqlCon())
{
var tran = conn.BeginTransaction();
{
conn.Execute(sqlStr,null, transaction: tran);
}
tran.Commit();
}
}
sw.Stop();
App.Log.Info($" BulkInsert 耗时 {sw.ElapsedMilliseconds} 毫秒 ");
}
public static MySqlConnection MySqlCon()
{
string msg;// = "";
string mysqlConnectionStr = ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString;
var connection = new MySqlConnection(mysqlConnectionStr);
try
{
connection.Open();
}
catch (Exception ex)
{
msg = $"MySQL数据库连接失败!请检查数据库是否正常 {ex.Message}";
MessageBox.Show(msg);
App.Log.Error(msg);
}
return connection;
}
|