MySqlBulkLoader 中文乱码
程序员文章站
2022-06-28 21:50:11
MySQL驱动: "MySqlConnector" GitHub地址:https://github.com/mysql net/MySqlConnector.git 文档地址:https://mysql net.github.io/MySqlConnector/ 代码插入之后发现出现中文乱码现象。 ......
mysql驱动:mysqlconnector
github地址:https://github.com/mysql-net/mysqlconnector.git
文档地址:https://mysql-net.github.io/mysqlconnector/
代码插入之后发现出现中文乱码现象。
原来的代码逻辑简略版
实现逻辑梳理,将数组写入csv,通过mysqlbulkloader批量插入
public async task bulkloadlocalcsvfile() { using (var connection = new mysqlconnection(getlocalconnectionstring())) { await connection.openasync(); var path = path.gettempfilename(); mysqlbulkloader bl = new mysqlbulkloader(connection); bl.filename = path; bl.tablename = "test"; 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。
csvhelper
- github地址:https://github.com/joshclose/csvhelper
- nuget地址:https://www.nuget.org/packages/csvhelper/12.1.2
指定 csvhelper.configuration.configuration
字符集
var configuration = new configuration { encoding = encoding.utf8 };
没能解决。
指定streamwriter字符集
var writer = new streamwriter(path, true, encoding.utf8)
不行。
指定mysqlbulkloader字符集
bl.characterset = "utf8";
乱码解决。
上一篇: 女友把我绿了又给我介绍一新的
下一篇: recyclerView滑动删除