mysql事务中出现异常没有被捕获,未捕获MySQL异常(C#)

My C# program works with a MySQL database.

For some reason the program cannot catch exceptions caused my the MySQL connection.

Example:

If I make the credentials in the connection string invalid, the program crashes like this (even when running in the debugger): http://imgur.com/SfzkVdW

The connection code is like this:

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

}

...

Any ideas for how I can improve things and start catching MySQL exceptions?

I have tried wrapping the code in the static constructor in a try-catch. That didn't help. The program still crashed in the same way.

Thanks.

Same code with the try-catch wrapper. It still fails with the same error: 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);

}

}

解决方案

Use the appropriate exception type in the catch block.

Use the appropriate MySQL classes.

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

}

}

}

Error Caught No Problem:

5d3233998ae91b546c7cfeb7ac56eab5.png

Add References screenshot:

a9cb49ecabca87e661c2afb81419ecdb.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值