以下讲的是如何把获取到的数据最短时间内插入到指定数据库方法。
把获取数据批量插入到数据库中:
代码:
class Program
{
static readonly string StrConnMsg = "server=127.0.0.1;port=3306;uid=root;pwd=a1234;database=usualtest;Charset=utf8;AllowUserVariables=True";
static readonly long totalRow = 100000;//要添加行数
static readonly int getRow = 1000; //定义这个是我为了在页面打印出所消耗时间
/// <summary>
/// 时间的转换
/// </summary>
/// <param name="l"></param>
/// <returns></returns>
static int GetMinute(long l)
{
return (Int32)l / 60000;
}
static void Main(string[] args)
{
//InsertOne();
InsertTwo();
}
#region 第一种一条条插入
static void InsertOne()
{
Console.WriteLine("采用一条一条插入的方式实现");
Stopwatch sw = new Stopwatch();
using (MySqlConnection conn = new MySqlConnection(StrConnMsg)) //using中会自动Open和Close 连接。
{
string sql = "INSERT INTO Product(Id,Name,Price) VALUES(@newid,@p,@d)";
conn.Open();
for (int i = 1; i <= totalRow; i++)
{
var Guiddata = Guid.NewGuid();
using (MySqlCommand cmd = new MySqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@newid", "" + Guiddata);
cmd.Parameters.AddWithValue("@p", "商品" + i);
cmd.Parameters.AddWithValue("@d", "店铺" + i);
sw.Start();
cmd.ExecuteNonQuery();
Console.WriteLine(string.Format("插入{0}条记录,已耗时{1}毫秒", i, sw.ElapsedMilliseconds));
}
if (i == getRow)
{
sw.Stop();
break;
}
}
}
Console.WriteLine(string.Format("插入{0}条记录,每{4}条的插入时间是{1}毫秒,预估总得插入时间是{2}毫秒,{3}分钟", totalRow, sw.ElapsedMilliseconds, ((sw.ElapsedMilliseconds / getRow) * totalRow), GetMinute((sw.ElapsedMilliseconds / getRow * totalRow)), getRow));
}
#endregion
#region 第二种使用MysqlBulkCopy批量加
static void InsertTwo()
{
Console.WriteLine("使用Bulk插入的实现方式");
Stopwatch sw = new Stopwatch();
DataTable dt = GetTableSchema();
using (MySqlConnection conn = new MySqlConnection(StrConnMsg))
{
conn.Open();
sw.Start();
for (int i = 1; i <= totalRow; i++)
{
DataRow dr = dt.NewRow();
dr[0] = Guid.NewGuid();
dr[1] = string.Format("商品", +i);
dr[2] = (decimal)i;
dt.Rows.Add(dr);
Console.WriteLine("DataTable中已添加{0}条数据", i);
}
dt.TableName = "Product";
Console.Write("已填充完DataTable是否进行一键入库?");
Console.ReadLine();
if (dt != null && dt.Rows.Count != 0)
{
BulkInsert.MySqlBulkInsert(dt, StrConnMsg);
sw.Stop();
}
Console.WriteLine(string.Format("插入{0}条记录共花费{1}毫秒,{2}分钟", totalRow, sw.ElapsedMilliseconds, GetMinute(sw.ElapsedMilliseconds)));
Console.ReadLine();
}
}
/// <summary>
/// 创建表结构,这个表结构对应的是数据库字段。
/// </summary>
/// <returns></returns>
public static DataTable GetTableSchema()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("Id",typeof(string)),
new DataColumn("Name",typeof(string)),
new DataColumn("Price",typeof(decimal))
});
return dt;
}
#endregion
上述是两种方法的对比,一种是使用一条一条添加到数据库(也就是一条一条的去执行一次添加语句),另外一个是使用MysqlBulkCopy进行的批量添加。
方法二:使用MysqlBulkCopy.dll地址在:https://download.csdn.net/download/qq_42005673/11453472
其中包含其上诉源码,及sql的批量插入和Mysql的批量插入Dll。