c# - C# 中的 SqlConnection - 安全编程实践

标签 c# .net

我在 MSDN 网站上找到这段代码 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx :

private static void OpenSqlConnection(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("State: {0}", connection.State);
    }
}

我的问题是...该站点还指出 .Open() 可以抛出 InvalidOperationExceptions 和 SqlExceptions,但这个示例看起来并没有处理它们。

这仅仅是因为他们对代码很简短,还是因为他们不值得在这里处理?它们可能以某种方式由 using 结构处理吗?

最佳答案

Is this just because they were being brief with the code, or is there a reason they're not worth handling here? are they possibly handld by the using construct in some way?

using 关键字是 try/finally 的语法糖,即使您引用的代码不会处理可能的异常,SQL 连接也会被正确处理.他们可能没有明确地处理可能的异常,因为许多人更喜欢让异常冒泡到最高层并在那里处理异常。

关于c# - C# 中的 SqlConnection - 安全编程实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10385235/

相关文章:

c# - urlencode问题

.net - 在 Visual Studio Express 2010 版本中是否有一种简单的方法来提取接口(interface)?

c# - 是否可以序列化或保存 viewbag 状态?

c# - AutoMapper 自定义映射

c# - 如何实现允许工作人员重新排队工作的有限并发工作队列

c# - 在 MVC 中填充下拉列表

c# - 定义动态数组

c# - 何时不使用 lambda 表达式

c# - 注册事件时执行操作?

c# - "SaveAs"Wordprocessingdocument (Open XML) 文件被锁定