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


最近搞 .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;

測試代碼:

 1 using System;
 2 using MySql.Data.MySqlClient;
 3 using Dapper;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 
 7 namespace ConsoleApp1
 8 {
 9 
10     public class CityEntity
11     {
12         public int ID { get; set; }
13         public string Name { get; set; }
14         public string CountryCode { get; set; }
15         public string District { get; set; }
16         public int Population { get; set; }
17 
18         public override string ToString()
19         {
20             return $"ID: {ID}, Name: {Name}, CountryCode: {CountryCode}, District: {District}, Population: {Population}";
21         }
22     }
23     public class CityRepository
24     {
25         public List<CityEntity> Get10Cities()
26         {
27             List<CityEntity> result;
28             using (var conn = new MySqlConnection("Host=172.16.1.197;Port=3306;Database=mars_xusinan;Uid=root;pwd=123456"))
29             {
30                 var sql = "SELECT * FROM city";
31                 result = conn.Query<CityEntity>(sql).ToList();
32             }
33 
34             return result;
35         }
36     }
37     class Program
38     {
39         static void Main(string[] args)
40         {
41             var repository = new CityRepository();
42             var cities = repository.Get10Cities();
43             cities.ForEach(e =>
44             {
45                 System.Console.WriteLine(e);
46             });
47         }
48     }
49 }
View Code

添加引用:用NuGet得到包

Dapper 

MySql.Data

安裝完后,報錯自然消失,大功告成,搞了2天,堅持不放棄。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM