use*_*745 11 c# sql using-statement
这是否可以使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果打开连接时出错,该怎么办?
using语句是try,最后是
no catch
因此,如果我抓到外面的使用支架,捕获会捕获连接打开错误吗?
如果没有,如何使用using上面显示的语句实现这一点?
Kev*_*nle 17
可以在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
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想捕获任何错误,那么你需要将所有内容包装在try- catchblock中.using块只是确保处理非托管资源,它们无法处理异常.
还有,SqlCommand实现IDisposable,所以我建议把它放在一个using块中.
| 归档时间: |
|
| 查看次数: |
36355 次 |
| 最近记录: |