System.NotSupportedException:“No data is available for encoding 1252. For information on defining a custom encoding

2023-02-17,,

最近搞 .net项目,Dapper连接Mysql时,运行报错:

System.NotSupportedException:“No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.”

解决办法:

新建项目,选择Visual C#   ->    .Net Core    ->    控制台应用(.Net Core)

数据库语句:

CREATE TABLE `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

测试代码:

 using System;
using MySql.Data.MySqlClient;
using Dapper;
using System.Collections.Generic;
using System.Linq; namespace ConsoleApp1
{ public class CityEntity
{
public int ID { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
public string District { get; set; }
public int Population { get; set; } public override string ToString()
{
return $"ID: {ID}, Name: {Name}, CountryCode: {CountryCode}, District: {District}, Population: {Population}";
}
}
public class CityRepository
{
public List<CityEntity> Get10Cities()
{
List<CityEntity> result;
using (var conn = new MySqlConnection("Host=172.16.1.197;Port=3306;Database=mars_xusinan;Uid=root;pwd=123456"))
{
var sql = "SELECT * FROM city";
result = conn.Query<CityEntity>(sql).ToList();
} return result;
}
}
class Program
{
static void Main(string[] args)
{
var repository = new CityRepository();
var cities = repository.Get10Cities();
cities.ForEach(e =>
{
System.Console.WriteLine(e);
});
}
}
}

添加引用:用NuGet得到包

Dapper

MySql.Data

安装完后,报错自然消失,大功告成,搞了2天,坚持不放弃。

System.NotSupportedException:“No data is available for encoding 1252. For information on defining a custom encoding的相关教程结束。

《System.NotSupportedException:“No data is available for encoding 1252. For information on defining a custom encoding.doc》

下载本文的Word格式文档,以方便收藏与打印。