在C#中使用MySqlBulkCopy类来批量复制数据到MySQL数据库,首先需要确保你的项目中已经引用了MySQL Connector。以下是使用MySqlBulkCopy的基本步骤:
1.安装MySQL Connector。
可以通过NuGet安装MySQL Connector:
2.在代码中引用必要的命名空间。
cs
using MySqlConnector;
3.连接串未添加AllowLoadLocalInfile=true
4.创建MySqlConnection对象并打开连接到目标MySQL数据库。
5.创建MySqlBulkCopy对象并设置相关属性。
6.使用WriteToServer方法将数据从DataTable或DbDataReader批量复制到数据库中。
示例代码:
cs
public bool SqlBulkAdd(DataTable dt, string tableName)
{
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
try
{
connection.Open();
MySqlBulkCopy bulkCopy = new MySqlBulkCopy(connection);// 创建MySqlBulkCopy对象
bulkCopy.DestinationTableName = tableName; // 目标表名
bulkCopy.ColumnMappings.AddRange(GetMySqlColumnMapping(dt));
MySqlBulkCopyResult result = bulkCopy.WriteToServer(dt); // dataTable是包含要复制数据的DataTable
Logger.Instance.DoSomesting = " 数据库访问";
Logger.Instance.Info("批处理数据导入:成功,MySqlBulkCopy");
return isSucess;
}
catch (Exception ex)
{
isSucess = false;
Logger.Instance.DoSomesting = " 数据库访问";
Logger.Instance.Info("批处理数据导入:异常,MySqlBulkCopy," + ex.Message);
return isSucess;
//throw ex;
}
finally
{
connection.Close();
}
}
}
private List<MySqlBulkCopyColumnMapping> GetMySqlColumnMapping(DataTable dataTable)
{
List<MySqlBulkCopyColumnMapping> colMappings = new List<MySqlBulkCopyColumnMapping>();
int i = 0;
foreach (DataColumn col in dataTable.Columns)
{
colMappings.Add(new MySqlBulkCopyColumnMapping(i, col.ColumnName));
i++;
}
return colMappings;
}
异常,To use MySqlBulkLoader.Local=true, set AllowLoadLocalInfile=true in the connection string. See https://fl.vu/mysql-load-data
解决方法:
sql
数据库连接字符串要加上"AllowLoadLocalInfile=true",如下:
const string ConnectionString = "server=localhost;port=3306;user=root;password=123456;database=mysql;SslMode = none;AllowLoadLocalInfile=true";
异常,Loading local data is disabled; this must be enabled on both the client and server sides
解决方法
mysql数据库开启允许本地导入数据的配置,命令如下:
sql
SET GLOBAL local_infile=1;//1表示开启,0表示关闭