未捕获MySQL异常(C#) [英] MySQL exceptions not caught (C#)

查看:211
本文介绍了未捕获MySQL异常(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C#程序可用于MySQL数据库.

My C# program works with a MySQL database.

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

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

示例:

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

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

连接代码如下:

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异常的任何想法吗?

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

我尝试将代码包装在try捕获中的静态构造函数中.那没有帮助.该程序仍然以相同的方式崩溃.

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.

谢谢.

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

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

推荐答案

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

Use the appropriate exception type in the 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();
        }
    }
}

没有遇到任何错误:

添加参考截图:

这篇关于未捕获MySQL异常(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆