C#using语句,SQL和SqlConnection

这是否可以使用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
没有捕获

因此,如果我抓到外面的使用支架,捕获器会捕获连接打开错误吗?

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

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

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

如果你想捕获任何错误,那么你需要在trycatch块中包装所有内容。 using块只需确保处理非托管资源,它们无法处理exception。

此外, SqlCommand实现了IDisposable ,所以我建议将它放在一个using块中。

只是明确地写出来:

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

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

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

不要为每行重新实例化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 } } } }