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
没有 catch
因此,如果我在 using 括号之外捕获,捕获会捕获连接打开错误吗?
如果没有,如何使用上面所示的 using
语句来实现这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
向数据库中的字段添加唯一索引并捕获错误。
不要为每一行重新实例化 SQL 连接。打开和关闭连接是资源密集型的。尝试这样的事情:
Add a unique index to the database for the fields and catch the error.
Don't reinstantiate the SQL Connection for each row. Opening and closing a connection is resource intensive. Try something like this:
是的,您可以将
using
块放在try
块中,下面的catch
将捕获与try< 相关的任何错误/代码> 块。
Yes, you can put the
using
block in atry
block, and the followingcatch
will catch any errors related to thetry
block.只要明确地写出来:
Just write it out explicitely:
如果您想捕获任何错误,那么您需要将所有内容包装在
try
-catch
块中。using
块只是确保释放非托管资源,它们无法处理异常。另外,
SqlCommand
实现了IDisposable
,因此我建议也将其放入using
块中。If you want to catch any error then you'll need to wrap everything in
try
-catch
block.using
blocks simply ensure that non-managed resources are disposed, they cannot handle exceptions.Also,
SqlCommand
implementsIDisposable
, so I'd suggest putting that in ausing
block as well.可以在 C# 中执行此操作(我还看到代码完全显示在 MSDN 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: