using语句,SQL和SqlConnection的C#的 [英] The C# using statement, SQL, and SqlConnection

查看:600
本文介绍了using语句,SQL和SqlConnection的C#的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能使用using语句C#SQL?

Is this possible using a using statement C# SQL?

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

如果打​​开连接?有一个误差

What if there’s a error while opening the connection?

using语句是尝试最后结果
 没有赶上

The using statement is try and finally
No catch

所以,如果我赶上用括号外将抓捉连接口的错误?

So if I catch outside the using brackets will the catch catch the connection opening error?

如果不是,如何使用以上所示的使用语句实现这个?

If not, how to implement this with using the using statement a shown above?

推荐答案

这有可能在C#中这样做(我也看到,code在MSDN正好显示<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx\">http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx).但是,如果你需要的防守和例如记录潜在的异常,这将有助于排除在生产环境中,你可以采取这种做法:

It's possible to do so in C# (I also see that code is exactly shown in MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx). However, if you need to be defensive and for example log potential exceptions which would help troubleshooting in a production environment, you can take this approach:

private static void CreateCommand(string queryString,
string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
           connectionString))
    {
        try
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (InvalidOperationException)
        {
            //log and/or rethrow or ignore
        }
        catch (SqlException)
        {
            //log and/or rethrow or ignore
        }
        catch (ArgumentException)
        {
            //log and/or rethrow or ignore
        }
    }
}

这篇关于using语句,SQL和SqlConnection的C#的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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