【问题标题】:Handle MySQL exceptions in Visual Studio在 Visual Studio 中处理 MySQL 异常
【发布时间】:2016-02-11 01:58:19
【问题描述】:

以下代码检查我是否可以连接到 MySQL 数据库。它在连接时工作正常,但当它无法连接时它会抛出错误而不是执行'Else'语句

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace MySQLConnection
{
    public partial class FrmConnection : Form
    {
        public FrmConnection()
        {
            InitializeComponent();
        }

        string connectionString = "host=192.168.0.91; database=c#1; user=test1; password=test1";
        private void button1_Click(object sender, EventArgs e)
        {
            using (MySqlConnection con= new MySqlConnection(connectionString))
            {
                con.Open();
                if(con.State==ConnectionState.Open)
                {
                    label1.Text = "Connection Established!";
                }
                else
                {
                    label1.Text = "Connection Error!";
                }
            }
        }
    }
}

我收到此错误

MySql.Data.dll 中出现“MySql.Data.MySqlClient.MySqlException”类型的未处理异常

附加信息:无法连接到任何指定的 MySQL 主机。

【问题讨论】:

    标签: c# mysql


    【解决方案1】:

    要处理异常,您可以这样做:

    using (MySqlConnection con= new MySqlConnection(connectionString))
        {
            try
            {
                con.Open();
                label1.Text = "Connection Established!";
            }
            catch(Exception ex)
            {
                label1.Text = "Connection Error!\n"+ex.Message;
            }
            finally
            {
                con.Close();
            }
        }
    

    很好解释:它将try打开连接并设置成功消息。
    如果失败,它会说连接失败并显示来自catched异常的错误消息。
    然后,在finally 块上,它会在trycatch 都执行完之后关闭连接。

    我不确定,但由于您使用的是using,因此您不需要 finally 块,因为using 函数会自动关闭连接。

    有关 try catch finally 块的 MSDN page 的更多信息。

    【讨论】:

    • 谢谢你这工作完美。我刚开始学习 C#,这个 try catch 方法在未来对我有很大帮助。干杯
    • C# 是一门非常好的语言,希望你会喜欢它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2018-04-01
    • 2017-01-27
    相关资源
    最近更新 更多