gpt4 book ai didi

c# - 未捕获 MySQL 异常 (C#)

转载 作者:可可西里 更新时间:2023-11-01 08:25:09 25 4
gpt4 key购买 nike

我的 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 block 中使用适当的异常类型。

使用适当的 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

关于c# - 未捕获 MySQL 异常 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com