MySQL 未捕获异常 (C#)

MySQL exceptions not caught (C#)

我的 C# 程序使用 MySQL 数据库。

由于某些原因,程序无法捕获导致我的 MySQL 连接的异常。

示例:

如果我使连接字符串中的凭据无效,程序将像这样崩溃(即使在调试器中 运行):http://imgur.com/SfzkVdW

连接代码是这样的:

using MySQLDriverCS;

namespace XXX
{
    public class Data
    {
        private static MySQLConnection con;

        static Data()
        {
            string connectionString = new MySQLConnectionString("XXX",
                "XXX",
                "XXX",
                "XXX").AsString;

            con = new MySQLConnection(connectionString + ";CharSet=utf8");
            con.Open(); // For testing the connection
            con.Close();
        }
...

关于如何改进并开始捕获 MySQL 异常有什么想法吗?

我试过将代码包装在 try-catch 中的静态构造函数中。那没有帮助。程序仍然以同样的方式崩溃。

谢谢。


与 try-catch 包装器相同的代码。它仍然失败并出现相同的错误:http://imgur.com/SfzkVdW

    static Data()
    {
        try
        {
            string connectionString = new MySQLConnectionString("XXX",
                "XXX",
                "XXX",
                "XXX").AsString;

            con = new MySQLConnection(connectionString + ";CharSet=utf8");
            con.Open(); // For testing the connection
            con.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

在 C# 中捕获或处理异常通常需要 try-catch 语句。

语法基本如下:

try
{
    // operation likely to cause error
} 
catch (Exception e){
    // handle error
    Console.WriteLine("Exception: " + e);
}

Console.Read();

所以将您的 con.Open() 逻辑包装在 try-catch 语句中,如下所示:

try
{
    Con.Open();
} 
catch (Exception e){
    // handle error
    Console.WriteLine("Possible MySQL Exception: " + e);
}

此外,您可以在 try-catch 语句的末尾添加一个 finally 块,无论是否处理异常,它都会执行其代码:

    try
{
    // attempt to do something here
    con.Open();
} 
catch (Exception e){
    // handle error
    Console.Writeline("Exception: " + e);
}
finally 
{
    Console.Writeline("This runs no matter if an exception is thrown or not!");
}

Console.Read();

在 catch 块中使用适当的异常类型。

使用适当的MySQL类.

using MySql.Data.MySqlClient;

// class level var or whatnot:
string connString = @"server=theHostName;userid=dbuser123;password=OpenSesame7;database=my_db_name";


public void connect()
{
    try
    {
        conn = new MySqlConnection(connString); // read above comments for (conn)
        conn.Open();
    }
    catch (MySqlException ex)
    {
        MessageBoxButtons buttons = MessageBoxButtons.OK;
        string s="MySqlException: "+ex.ToString();
        MessageBox.Show(s,"Error",buttons);
    }
    finally
    {
        if (conn != null)
        {
            //conn.Close();
        }
    }
}

错误没问题:

添加参考截图: