C#中的using语句,SQL和SqlConnection

13

使用C# SQL中的using语句是否可行?

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

如果在打开连接的过程中出现错误怎么办?

using语句是try和finally,而不是catch。

因此,如果我在using括号外部捕获异常,那么是否可以捕获到连接打开时的错误呢?

如果不能,如何使用上述using语句实现此功能?

5个回答

19

在C#中可以这样做(我还看到代码完全显示在MSDN上http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx)。但是,如果您需要采取防御性措施,例如记录潜在异常以帮助生产环境的故障排除,可以采取以下方法:

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

5
如果你想捕获任何错误,那么你需要将所有内容都包装在try-catch块中。using块只是确保非托管资源被处理,不能处理异常。
另外,SqlCommand实现了IDisposable接口,因此我建议也将其放入using块中。

2

请明确写出来:

SqlConnection connection = new SqlConnection(connectionString);
try
{
    using (SqlCommand command = new SqlCommand(queryString, connection))
    {
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}
catch (Exception e)
{
    // ...handle, rethrow. Also, you might want to catch
    // more specific exceptions...
}
finally
{
    connection.Close();
}

怎么不可以呢?使用SqlConnection在using块中会产生这样的效果。 - Willem van Rumpt
1
仍然不需要手动执行“using”操作;可以使用以下代码:try { using(var connection = new SqlConnection(connectionString) {...} } catch (Exception e) {...} - 不需要finally或显式的connection.Close() - Marc Gravell
同意,这只是我个人在这些情况下编写它(try-catch-finally)的首选方式;在我看来,它排列得很好。但当然,每个人都有自己的喜好。轻松一点:真的吗?对于一个在2010年就已经问答完毕的问题发表评论? - Willem van Rumpt
这与Using块不同,因为End Using将调用connection.Dispose - Matt Wilko
就像 SqlConnection.Close() 一样(更确切地说:Dispose() 调用 Close()), - Willem van Rumpt
显示剩余2条评论

1

是的,你可以将 using 块放在一个 try 块中,接下来的 catch 将会捕获与 try 块相关的任何错误。


0

为字段在数据库中添加唯一索引,并捕获错误。

不要为每一行重新实例化SQL连接。打开和关闭连接会消耗资源。尝试像这样做:

protected void btn_insert_Click(object sender, EventArgs e)
{
    string connStr = "your connection string";
    SqlCommand cmd;

    using (SqlConnection con = new SqlConnection(connStr))
    {
        con.Open();
        foreach (GridViewRow g1 in GridView1.Rows)
        {
            try
            {
                cmd = new SqlCommand("command text", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException sqlEx)
            {
                //Ignore the relevant Sql exception for violating a sql unique index
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接