使用c#将ExcelSheet数据插入MySql数据库

时间:2017-10-24 07:34:52

标签: c# mysql

在使用MS SQL的解决方案中,代码如下所示。  现在我尝试为MySQL做类似的事情。我尝试使用MysqlBulkLoader,但它无法正常工作

SqlBulkCopy objbulk = new SqlBulkCopy(connect);
    //MySqlBulkLoader objbulk = new MySqlBulkLoader(connect);

    //assigning Destination table name
    objbulk.DestinationTableName = "barter_proposals";
    //Mapping Table column
    objbulk.ColumnMappings.Add("company", "company");
    objbulk.ColumnMappings.Add("website_a", "website_a");
    objbulk.ColumnMappings.Add("email_id", "email_id");
    objbulk.ColumnMappings.Add("contact_name", "contact_name");
    //inserting Datatable Records to DataBase
    connect.Open();
    objbulk.WriteToServer(Exceldt);
    connect.Close();

1 个答案:

答案 0 :(得分:1)

MySqlBulkLoader使用与SqlBulkCopy完全不同的方式执行批量插入/更新:它使用基于文件的输入(例如TXT或CSV),而不是直接使用DataTable实例。要解决此问题,您可以将DataTable导出为CSV文件,并按以下示例MySqlBulkLoader阅读内容:

1)DataTable到CSV转换

using (var sw = new StreamWriter("/path/to/source/file.csv", false))
{
    // assume Exceldt is your 'DataTable' object
    int colCount = Exceldt.Columns.Count;
    foreach (DataRow row in Exceldt.Rows)
    {
        for (int i = 0; i < colCount; i++)
        {
            if (!Convert.IsDBNull(row[i]))
            {
                sw.Write(row[i].ToString());
            }
            if (i < colCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
    }
}

2)MySqlBulkLoader从CSV文件批量插入

// creating bulk loader instance
MySqlBulkLoader objbulk = new MySqlBulkLoader(connect);
objbulk.TableName = "barter_proposals";
objbulk.Timeout = 600; // set command timeout
objbulk.FieldTerminator = ",";
objbulk.LineTerminator = "\r\n";
objbulk.FileName = "/path/to/source/file.csv";
objbulk.NumberOfLinesToSkip = 1; // adjust this depending on CSV file headers

objbulk.Load();

// delete the CSV file here (optional)

参考文献:

Using the MySqlBulkLoader Class (5.13) - MySQL Docs

MySQL - Bulk data import using .NET Connector MySqlBulkLoader Class

MySqlBulkLoader with Column Mapping?