MySqlBulkLoader 中文亂碼

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文件的字符集
  • 須要指定StreamWriter字符集
  • 須要指定MySqlBulkLoader字符集

指定csv文件的字符集

寫CSV文件藉助的是開源包CsvHelper。
CsvHelpersql

指定 CsvHelper.Configuration.Configuration字符集數組

var configuration = new Configuration
{
     Encoding = Encoding.UTF8
 };

沒能解決。async

指定StreamWriter字符集

var writer = new StreamWriter(path, true, Encoding.UTF8)

不行。code

指定MySqlBulkLoader字符集

bl.CharacterSet = "UTF8";

亂碼解決。文檔

相關文章
相關標籤/搜索