MySQL Connector for .NET填充DataSet失败:是Bug还是代码问题?
MySQL DataAdapter填充DataSet失败,抛出KeyNotFoundException
Connection_String用于获取MySQL连接信息,Table_Name为从Tables枚举中获取的表名。这段代码用于查询表中active字段值为1的数据,MySQL连接成功,但MySqlDataAdapter填充DataSet(ds)失败,抛出KeyNotFoundException异常。
环境信息
- MySQL版本:10.10.2
- MySQL Connector for .NET版本:8.0.22
- 数据库字符集:无utf8mb3字符集,默认字符集为utf8mb4,所有表均设置为utf8mb4或utf16字符集
代码实现
public class SQL_Comm { public bool Select_Check_Activate(int Tbl_Pram) { //DataSet ds = null; string sql = ""; string Equip, Line, Sensor = ""; string Table_Name = Tables(Tbl_Pram); //Enum.GetName(string, typeof(Tables), Tbl_Pram); DataSet ds = null; bool is_activate = false; MySqlCommand Cmd; try { MySqlConnection Conn = new MySqlConnection(Connection_String()); if (Conn != null) Conn.Open(); if (Conn.State == ConnectionState.Open && Table_Name != "") { sql = string.Format("SELECT * FROM " + Table_Name + " WHERE active = '1'"); MySqlDataAdapter adp = new MySqlDataAdapter(sql, Conn); adp = new MySqlDataAdapter(sql, Conn); ds = new DataSet(); adp.Fill(ds, Table_Name); foreach(var Table_Contents in ds.Tables[0].Rows) { } } Conn.Dispose(); } catch (Exception ex) { } return is_activate; } }
抛出的异常信息
2023-02-24 00:00:10,249[DEBUG]/DB Selection Error : System.Collections.Generic.KeyNotFoundException: 指定的键不在字典中。(The given key was not present in the dictionary) 位置: System.ThrowHelper.ThrowKeyNotFoundException() 位置: System.Collections.Generic.Dictionary`2.get_Item(TKey key) 位置: MySql.Data.MySqlClient.MySqlField.SetFieldEncoding() 位置: MySql.Data.MySqlClient.NativeDriver.GetColumnData(MySqlField field) 位置: MySql.Data.MySqlClient.NativeDriver.GetColumnsData(MySqlField[] columns) 位置: MySql.Data.MySqlClient.Driver.GetColumns(Int32 count) 位置: MySql.Data.MySqlClient.ResultSet.LoadColumns(Int32 numCols) 位置: MySql.Data.MySqlClient.ResultSet..ctor(Driver d, Int32 statementId, Int32 numCols) 位置: MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force) 位置: MySql.Data.MySqlClient.MySqlDataReader.NextResult() 位置: MySql.Data.MySqlClient.MySqlDataReader.Close() 位置: MySql.Data.MySqlClient.MySqlCommand.ResetReader() 位置: MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) 位置: System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) 位置: System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) 位置: System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
已尝试的解决方案
- 更新MySQL Connector(MySql.Data.dll)版本至6.10.7 ~ 8.0.22范围内的所有可用NuGet包
- 升级MySQL服务器至新版本
- 将数据库及所有表的字符集设置为utf8mb4(也尝试过utf16)
- 更新.NET Framework版本
内容的提问来源于stack exchange,提问作者prescott
相关产品推荐
相关产品推荐

