11

这可能使用 using 语句 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();
    }
}

如果打开连接时出现错误怎么办?

using 语句是 try 和 finally
没有 catch

因此,如果我在使用括号之外捕获,捕获会捕获连接打开错误吗?

如果没有,如何使用using上面显示的语句来实现这一点?

4

5 回答 5

18

可以在 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
        }
    }
}
于 2010-06-20T12:02:53.680 回答
5

如果您想捕获任何错误,那么您需要将所有内容包装在try-catch块中。using块只是确保释放非托管资源,它们不能处理异常。

另外,SqlCommandimplements IDisposable,所以我建议也把它放在一个using块中。

于 2010-06-20T11:48:19.313 回答
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();
}
于 2010-06-20T11:49:30.307 回答
1

是的,您可以将using块放入块中try,以下catch将捕获与try块相关的任何错误。

于 2010-06-20T11:48:46.440 回答
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
            }
        }
    }
}
于 2016-07-01T11:19:24.293 回答