SqlConnection.Close()里面使用语句 [英] SqlConnection.Close() inside using statement
问题描述
您的所有答案都很实用。感谢所有努力回答我的问题的人。 Cheers:)
All of your answers were useful. Thank to all who put effort on answering my question. Cheers :)
我正在使用此代码:
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();
我的意思是...它不显示任何错误,没有任何问题...最好先关闭它吗?
Is it wrong if I don't add sqlConnection.Close();
before disposing it? I mean... It's not showing any errors, no problems at all... Is it better to Close it first? If yes, why?
推荐答案
不需要关闭或处置
使用
块会为你照顾。
No need to Close or Dispose
the using
block will take care of that for you.
如 MSDN :
以下示例创建一个SqlConnection ,打开它,显示一些
的属性。连接在使用块的末端
处自动关闭。
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);
}
}
这篇关于SqlConnection.Close()里面使用语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!