MySQL驅動:MySqlConnector
GitHub地址:https://github.com/mysql-net/MySqlConnector.git
文檔地址:https://mysql-net.github.io/MySqlConnector/mysql
代碼插入以後發現出現中文亂碼現象。git
實現邏輯梳理,將數組寫入csv,經過MySqlBulkLoader批量插入github
public async Task BulkLoadLocalCsvFile<T>(IEnumerable<T> dataSource, string tableName) { using (var connection = new MySqlConnection(GetLocalConnectionString())) { await connection.OpenAsync(); var path = Path.GetTempFileName(); MySqlBulkLoader bl = new MySqlBulkLoader(connection); bl.FileName = path; bl.TableName = tableName; bl.FieldTerminator = ","; bl.FieldQuotationCharacter = '"'; bl.FieldQuotationOptional = true; bl.Local = true; using (var writer = new StreamWriter(path)) { var configuration = new Configuration { HasHeaderRecord = false, }; using (var csv = new CsvWriter(writer, configuration)) { csv.WriteRecords(dataSource); var writerConfiguration = csv.Context.WriterConfiguration; var map = writerConfiguration.Maps.Find<T>(); foreach (var memberMap in map.MemberMaps) { var memberName = memberMap.Data.Member.Name; loader.Columns.Add(memberName); } } } int rowCount = await bl.LoadAsync(); File.Delete(path); } }
寫CSV文件藉助的是開源包CsvHelper。
CsvHelpersql
指定 CsvHelper.Configuration.Configuration
字符集數組
var configuration = new Configuration { Encoding = Encoding.UTF8 };
沒能解決。async
var writer = new StreamWriter(path, true, Encoding.UTF8)
不行。code
bl.CharacterSet = "UTF8";
亂碼解決。文檔