C# 连接mysql填坑
1,vs2013 使用 MySqlConnector 1.0.0.0 ,mysql版本8.0
2,连接地址: string myConnectionString = "server=192.168.1.0;uid=root;pwd=pwd;database=test;AllowLoadLocalInfile=true;Connect Timeout=300";
坑1:本地连接远程数据库,没有问题,上了生产就连不上。报错 Expected to read 4 header bytes but only received 0,参考连接:https://github.com/mysql-net/MySqlConnector/issues/540
设置连接时间:
SHOW GLOBAL VARIABLES LIKE '%timeout%';
SET GLOBAL connect_timeout = 300;
坑2:使用这个插件做批处理,需要在客户端设置 AllowLoadLocalInfile=true;服务端设置
SHOW GLOBAL VARIABLES LIKE 'local_infile';
SET GLOBAL local_infile = 'ON';
下面的代码是使用该 DLL 的批处理功能
public static async Task SqlBulkInsert(DataTable dt, string tableName, string connStr) { try { using (var conn = new MySqlConnection(connStr)) { try { conn.Open(); var bulkCopy = new MySqlBulkCopy(conn); bulkCopy.DestinationTableName = tableName; bulkCopy.WriteToServer(dt); } finally { if (conn.State != ConnectionState.Closed) { conn.Close(); } } } } catch (Exception ex) { throw ex; } }
项目使用框架太老,就导致用的东西太老了。