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 Dispose
的using
模块会照顾的,对于你.
如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)
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
您必须通过调用Close或Dispose显式关闭连接。Close和Dispose在功能上是等效的。
因此,调用Dispose
(隐式地,甚至使用using
)也会像以前一样覆盖您的基础。
值得一提的,我也认为,虽然没有具体到你的情况,Close
会当事情被包裹在一个始终有效地称为using
声明-这可能不会是它应该被忽略的情况和异常发生不正确的try
/ catch
/ finally
处理。
不加sqlConnection.Close()有错吗?在处理它之前
不,只要您在Using
. 当您离开 using 范围时,Dispose
将调用 sql 连接。这将关闭现有连接并释放所有资源。
归档时间: |
|
查看次数: |
29281 次 |
最近记录: |