未捕获MySQL异常(C#)

时间:2016-07-09 02:03:41

标签: c# mysql connection-string

我的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);
        }
    }

2 个答案:

答案 0 :(得分:2)

在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();
        }
    }
}

错误没问题:

enter image description here

添加参考资料截图:

enter image description here

答案 1 :(得分:0)

在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);
}

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

    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();