C#MySQL/连接器编号始终为0 [英] C# MySQL/Connector Number always 0

查看:71
本文介绍了C#MySQL/连接器编号始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

connectionString = "SERVER=localhost;DATABASE=NT;UID=" + dbuser + ";PASSWORD=" + dbpass + ";";

connection = new MySqlConnection(connectionString);

OpenConnection();


//open connection to database
    private bool OpenConnection()
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (MySqlException ex)
        {
            //The two most common error numbers when connecting are as follows:
            //0: Cannot connect to server.
            //1045: Invalid user name and/or password.
            switch (ex.Number)
            {
                case 0:
                    Console.WriteLine(" >>>> Cannot contact MySQL Server ");//MessageBox.Show("Cannot connect to server.  Contact administrator");
                    break;

                case 1045:
                    Console.WriteLine(" >>>> Invalid username/password, please try again");
                    break;

                case 1042:
                    Console.WriteLine(" >>>> Unable to resolve DNS");
                    break;
            }
            return false;
        }
    }

上面的代码已成功连接到本地主机数据库并登录,但是数据库"NT"不存在(我知道),但是ex.Number属性设置为0 错误的用户名/密码组合也导致了同样的问题. 异常消息/文本为我提供了错误的字符串,但数字字段始终设置为0.我们将不胜感激任何帮助.

The code above is successfully connecting to the localhost database and logging in but the database "NT" doesn't exist (which I know) but the ex.Number property is set to 0 I also got the same issue with wrong username/password combo. The exception message/text gives me the string of the error but the number field is always set to 0. Any help would be greatly appreciated.

非常感谢, 本

编辑/更新

这2个屏幕抓图之间的唯一区别是,我将NT更改为测试(NT不存在(该消息正确报告了消息,但数字不正确)并且测试确实存在)

The only difference between the 2 screengrabs is that I changed the NT to test (NT doesn't exist (which the message reports correctly but not the number) and test does exist)

我想知道这是否是预期的行为?基本上是因为该数据库不存在而拒绝连接吗?

I'm wondering if this is maybe intended behaviour? Is it basically refusing the connection because that DB doesn't exist?

推荐答案

我正在使用MySql Connector .Net 6.9.4,也遇到了此问题.我发现有一个MySqlException类型的InnerException,它具有错误号.您可以尝试我的助手方法:

I am using MySql Connector .Net 6.9.4 and also had this issue. I found out that there is an InnerException of type MySqlException that has the Error Number. You can try my Helper Method:

public static int GetExceptionNumber(MySqlException my)
{
    if (my != null)
    {
        int number = my.Number;
        //if the number is zero, try to get the number of the inner exception
        if (number == 0 && (my = my.InnerException as MySqlException) != null)
        {
            number = my.Number;
        }
        return number;
    }
    return -1;
}

问候

坦率

这篇关于C#MySQL/连接器编号始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆