本文介绍了尝试打开 MySQL 连接时可能导致 KeyNotFoundException 的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 C# 代码连接我的数据库,但在调试器访问 MySqlConnection Open 方法时收到 KeyNotFoundException.

我已经尝试将我的 connectionString 更改为另一个模板,重新启动我的 SQL 服务器,并手动验证我的服务器详细信息(用户名、密码等...)

//设置我的连接数据私有无效初始化(){服务器 = "127.0.0.1";数据库 = "数据库";uid = "root";密码 = "123456";字符串连接字符串;connectionString = "SERVER=" + 服务器 + ";"+数据库="+数据库 + ";"+ "uid=" + uid + ";"+ "PWd=" + 密码 + ";";connection = new MySqlConnection(connectionString);}//打开连接私人布尔OpenConnection(){尝试 {connection.Open();//这是我得到异常的地方返回真;}}

因为我除了连接,我得到了下一个例外:

System.Collections.Generic.KeyNotFoundException:字典中不存在给定的键.在 System.Collections.Generic.Dictionary`2.get_Item(TKey 键)在 MySql.Data.MySqlClient.CharSetMap.GetCharacterSet(DBVersion 版本,字符串 CharSetName)在 MySql.Data.MySqlClient.CharSetMap.GetEncoding(DBVersion 版本,字符串 CharSetName)在 MySql.Data.MySqlClient.Driver.Configure(MySqlConnection 连接)在 MySql.Data.MySqlClient.MySqlConnection.Open()在 sqlTesting.DBConnect.OpenConnection() 在 d:\Users\moshe\Documents\Visual Studio 2015\Projects\sqlTesting\sqlTesting\DBConnect.cs:line 40

解决方案

您应该尝试在 General 下的 Options 选项卡中删除 collat​​ion-server 设置code> 设置并重新启动您的 MySQL 服务器以解决此问题.

您可以简单地将 charset 添加到连接字符串中:

Server=127.0.0.1;Port=3306;Database=database;User ID=root;Password=123456;CharSet=utf8;

如果您的框架是 .NET,那么您需要做的就是确保您的MySql.Data.dll"与相应版本保持同步.

I trying to connect my database using C# code, but getting a KeyNotFoundException when the debugger gets to MySqlConnection Open method.

I Have tried changing my connectionString to another template, restarting my SQL server, and manually validating my server details (Username, Password ETC...)

//setting my connection data
private void Initialize() {
    server = "127.0.0.1";
    database = "database";
    uid = "root";
    password = "123456";
    String connectionString;
    connectionString = "SERVER=" + server + ";" + "DATABASE=" +
    database + ";" + "Uid=" + uid + ";" + "PWd=" + password + ";";
    connection = new MySqlConnection(connectionString);
}


//Opening the connection
private bool OpenConnection() {
    try {
        connection.Open();//This is where I get my Exception
        return true;
    }
}

As I except connection I am getting the next Exception:


解决方案

You should try removing collation-server settings in your Options tab under General settings and restart your MySQL server to resolve this issue.

OR

You can simply add the charset to the connection string:

Server=127.0.0.1;Port=3306;Database=database;User ID=root;Password=123456;CharSet=utf8;

OR

If your framework is .NET, then all you need to do is to make sure that your 'MySql.Data.dll' is up to date with the corresponding version.

这篇关于尝试打开 MySQL 连接时可能导致 KeyNotFoundException 的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:14