c# - SqlConnection.Close() 在 using 语句中

标签 c# sql .net sql-server database

我正在使用这段代码:

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

在处理之前不加sqlConnection.Close();是不是错了?我是说。它没有显示任何错误,根本没有问题。最好先关闭它吗?如果是,为什么?

最佳答案

无需Close or Dispose using block 将为您处理。

MSDN 所述:

The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block.

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

关于c# - SqlConnection.Close() 在 using 语句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18588049/

相关文章:

.net - WPF:如何使 Canvas 自动调整大小?

c# - Xamarin.iOS : Black screen after launch screen when no storyboard

C#角色服装系统

java - 如何从 SQL 中的非别名内联函数列标题中进行选择?

sql 用自身和额外的字符串更新一个字段

sql - 如何动态选择非空值列?

c# - Xamarin.Forms Shell GoToAsync 在 iOS 中无法按预期工作

c# - LINQ 查询 XML 文件以获取子标签

.net - 在Visual Studio中签名程序集

.net - 如何重用 GridViewColumn CellTemplate 并允许不同的绑定(bind)?