SqlConnection.Close()里面使用语句

Etr*_*rit 30 .net c# sql database using

我正在使用此代码:

    public void InsertMember(Member member)
    {
        string INSERT = "INSERT INTO Members (Name, Surname, EntryDate) VALUES (@Name, @Surname, @EntryDate)";

        using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
        {
            sqlConnection.Open();

            using (SqlCommand sqlCommand = new SqlCommand(INSERT, sqlConnection))
            {
                sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = member.Name;
                sqlCommand.Parameters.Add("@Surname", SqlDbType.VarChar).Value = member.Surname;
                sqlCommand.Parameters.Add("@EntryDate", SqlDbType.Date).Value = member.EntryDate;

                sqlCommand.ExecuteNonQuery();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果我sqlConnection.Close();在处理它之前不添加它是错误的吗?我的意思是.它没有显示任何错误,也没有任何问题.首先关闭它会更好吗?如果是,为什么?

Dar*_*ren 38

不需要Close or Disposeusing模块会照顾的,对于你.

MSDN所述:

以下示例创建一个SqlConnection,打开它,显示其一些属性.连接在使用块结束时自动关闭.

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);
    } 
}
Run Code Online (Sandbox Code Playgroud)

  • 如果代码具有连接,可以吗?Close(); 就在您倒数第二个大括号'}'之前?当using块尝试关闭已被代码关闭的连接时,这会引发异常吗? (2认同)

Sur*_*ngh 10

using statement ensures that Dispose is called,而你是调用对象的方法时,即使异常.You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; 实际上,这就是编译器如何翻译 using语句.MSDN

最终你的代码行

  using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
Run Code Online (Sandbox Code Playgroud)

try finally block通过编译器调用转换为正常IDisposable object in the finally


Gra*_*mas 5

根据MSDN文档中的Close方法

您必须通过调用CloseDispose显式关闭连接。CloseDispose在功能上是等效的。

因此,调用Dispose(隐式地,甚至使用using)也会像以前一样覆盖您的基础。

值得一提的,我也认为,虽然没有具体到你的情况,Close会当事情被包裹在一个始终有效地称为using声明-这可能不会是它应该被忽略的情况和异常发生不正确的try/ catch/ finally处理。


Ehs*_*san 5

不加sqlConnection.Close()有错吗?在处理它之前

不,只要您在Using. 当您离开 using 范围时,Dispose将调用 sql 连接。这将关闭现有连接并释放所有资源。