我正在使用这段代码:
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/