簡體   English   中英

未捕獲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);
        }
    }

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

錯誤沒問題:

在此輸入圖像描述

添加參考截圖:

在此輸入圖像描述

捕獲或處理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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM