使用C#查询MySQL时报“给定键不在字典中”错误的求助
问题描述
我们维护的系统基于旧版本.NET Framework(版本:4.0.30319.42000),测试时安装了MySql.Data.6.10.9包。示例程序可成功连接至MySQL v8.0.32,但执行select version();时触发错误:执行查询出错: The given key was not present in the dictionary.
测试输出
.Net版本: 4.0.30319.42000 尝试打开连接... 连接成功! 执行查询出错: The given key was not present in the dictionary. Press any key to continue . . .
已尝试的连接字符串
server=192.168.56.5;uid=root;port=3306;database=test-source;pwd=mysql_root_passwordserver=192.168.56.5;uid=root;port=3306;database=test-source;charset=utf8mb4;pwd=mysql_root_password
两种连接字符串均出现相同错误,此前参考的调整连接字符集的方案无效,希望排查是否有遗漏的解决点。
完整示例代码
using System; using MySql.Data.MySqlClient; class Program { static void Main(string[] args) { Console.WriteLine(".Net版本: " + Environment.Version.ToString()); string connectionString = "server=192.168.56.5;uid=root;port=3306;database=test-source;pwd=mysql_root_password"; try { using (var connection = new MySqlConnection(connectionString)) { Console.WriteLine("尝试打开连接..."); connection.Open(); if (connection.State == System.Data.ConnectionState.Open) { Console.WriteLine("连接成功!"); // 获取MySQL版本 try { string query = "SELECT VERSION();"; using (var command = new MySqlCommand(query, connection)) { string version = command.ExecuteScalar().ToString(); Console.WriteLine("MySQL版本: " + version); } } catch (Exception ex) { Console.WriteLine("执行查询出错: " + ex.Message); } } else { Console.WriteLine("连接打开失败。"); } } } catch (MySqlException ex) { Console.WriteLine("MySQL异常: " + ex.Message); } catch (Exception ex) { Console.WriteLine("通用异常: " + ex.Message); } } }
内容的提问来源于Stack Exchange,提问作者Mike
相关产品推荐
相关产品推荐

