如果无法访问SQL服务器... [英] If SQL server could not be reached...

查看:76
本文介绍了如果无法访问SQL服务器...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码连接到SQL数据库。无法访问SQL服务器时应该在何处以及如何进行异常处理?





I use this code to connect to the SQL database. Where and how should I make the exception when the SQL server could not be reached?


private void BT_AanmeldenAanmelden_Click(object sender, EventArgs e)
{
    this.Cursor = Cursors.WaitCursor;

    using (connection = new SqlConnection(connectionstring))

    using (SqlDataAdapter adapter = new SqlDataAdapter("Select Count(*) From Users Where Email = '" + TX_AanmeldenGebruikersnaam.Text + "' and Wachtwoord = '" + TX_AanmeldenWachtwoord.Text + "'", connection))
    {
        DataTable dt = new DataTable();
        adapter.Fill(dt);

        if (dt.Rows[0][0].ToString() == "1")
        {
            Progres_Login.Visible = true;
            TimerLogin.Start();
            this.Cursor = Cursors.Default;
        }
        else
        {
            this.Cursor = Cursors.Default;
            MessageBox.Show("De door u ingevulde gebruikersnaam en wachtwoord zijn incorrect", "##**## | Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
    }
}

推荐答案

try{
    adapter.Fill(dt);
}
catch (Exception exp)
{
    // do something
}





这是不好的做法但要捕获异常,您可以找出当SQL不可用时引发的具体异常,并专门捕获这些异常以提供更有针对性的消息。



It's bad practice to catch "Exception" though, you can find out what specific exceptions are raised when SQL isn't available and catch those specifically to give a more targeted message.


这篇关于如果无法访问SQL服务器...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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