加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将DataTable批量复制到MySQL(类似于System.Data.SqlClient

发布时间:2020-12-16 01:21:46 所属栏目:百科 来源:网络整理
导读:我正在将我的程序从Microsoft SQL Server迁移到 MySQL.一切正常,除了批量复制的一个问题. 在使用MS SQL的解决方案中,代码如下所示: connection.Open();SqlBulkCopy bulkCopy = new SqlBulkCopy(connection);bulkCopy.DestinationTableName = "testTable";bu
我正在将我的程序从Microsoft SQL Server迁移到 MySQL.一切正常,除了批量复制的一个问题.

在使用MS SQL的解决方案中,代码如下所示:

connection.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(connection);
bulkCopy.DestinationTableName = "testTable";
bulkCopy.WriteToServer(rawData);

现在我尝试为MySQL做类似的事情.因为我认为会有糟糕的性能,所以我不想将DataTable写入CSV文件,并使用MySqlBulkLoader类从那里进行插入.

任何帮助将受到高度赞赏.

解决方法

Because I think there would be bad performance I don’t want to write the DataTable to a CSV file and do the insert from there with the MySqlBulkLoader class.

不排除基于毫无根据的假设的可能解决方案.我刚刚在Transaction中使用标准的MySqlDataAdapter #Update()测试了从System.Data.DataTable插入100,000行到MySQL表中.它一直需要大约30秒才能运行:

using (MySqlTransaction tran = conn.BeginTransaction(System.Data.IsolationLevel.Serializable))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        cmd.Connection = conn;
        cmd.Transaction = tran;
        cmd.CommandText = "SELECT * FROM testtable";
        using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
        {
            da.UpdateBatchSize = 1000;
            using (MySqlCommandBuilder cb = new MySqlCommandBuilder(da))
            {
                da.Update(rawData);
                tran.Commit();
            }
        }
    }
}

(我为UpdateBatchSize尝试了几个不同的值,但它们似乎没有对经过的时间产生重大影响.)

相比之下,使用MySqlBulkLoader的以下代码只需要5或6秒就可以运行…

string tempCsvFileSpec = @"C:UsersGordDesktopdump.csv";
using (StreamWriter writer = new StreamWriter(tempCsvFileSpec))
{
    Rfc4180Writer.WriteDataTable(rawData,writer,false);
}
var msbl = new MySqlBulkLoader(conn);
msbl.TableName = "testtable";
msbl.FileName = tempCsvFileSpec;
msbl.FieldTerminator = ",";
msbl.FieldQuotationCharacter = '"';
msbl.Load();
System.IO.File.Delete(tempCsvFileSpec);

…包括从DataTable转储100,000行到临时CSV文件(使用类似于this的代码)的时间,从该文件批量加载,以及之后删除文件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读