c# - 由于 KeyNotFoundException,无法连接到 MySQL 数据库

标签 c# mysql keynotfoundexception

不确定为什么我每次尝试连接时都会收到错误消息。我尝试了很多东西。当我在手动连接时输入错误的密码时,它会显示未授予访问权限或其他任何内容,所以我知道它已连接但是当它连接时我收到这个奇怪的错误。

An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll Additional information: The given key was not present in the dictionary.

对于本地主机,当我有这个连接字符串时它可以工作。

server=localhost; port=3306; USER ID=root; password=***; database=database;

但是当我更改服务器用户 ID 和密码时,它决定不起作用。

cn.Open()处抛出异常;

     private void button1_Click(object sender, EventArgs e)
    {
        MySqlConnection cn = new MySqlConnection();
        cn.ConnectionString = "server=db4free.net ;port=3306; 
                               user=goof; password=pwd; database=s;";
        cn.Open();
        MySqlCommand cmd = new MySqlCommand("select * from users where
                                             username = '" 
                                             + textBox1.Text + "',
                                             and password = '" 
                                             + textBox2.Text + "'", cn);
        MySqlDataReader dr;
        dr = cmd.ExecuteReader();
        int count = 0;

        while(dr.Read())
        {
            count += 1;
        }
        if(count == 1)
        {
            MessageBox.Show("success");
        }
        else
        {
            MessageBox.Show("error");
        }
    }

最佳答案

问题是 user=goof 字段应该是 user id=goof

将您的连接字符串更改为:

cn.ConnectionString = "server=db4free.net ;port=3306; USER ID=goof; password=pwd; database=s;";

关于c# - 由于 KeyNotFoundException,无法连接到 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158658/

相关文章:

c# - 您可以在运行时更改 Type 的 Name 属性的值吗?

c# - .NET C# socket 在两个不同的线程上发送

c# - 从蛋糕脚本中将警告消息记录在文本文件中

php - 使用 mysql 进行计算,我在计算时遇到了麻烦

ruby-on-rails - 如何在 Ruby/Rails 中使用 MySQL 的 load 命令?

mysql - 对于该服务器版本,其显示在此位置无效

c# - 使用 HtmlEntity.DeEntitize() 方法的 KeyNotFoundException

c# - Asp.net 核心 2.1 UseHttpsRedirection 在 IIS 中不起作用