可能重複:
Trying to understand the ‘using’ statement better使用使用處置資源
我真的閱讀所有其他職位,但沒有人真正回答我的問題。
這是我的函數返回一個表
public DataTable ReturnTable()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(mainConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
SQL = " SELECT * from table";
cmd.CommandText = SQL;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return dt;
}
什麼是以前的優勢,針對以下(即我總是用之前發現「使用」的一個):
public DataTable ReturnTable()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(mainConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
SQL = " SELECT * from table";
cmd.CommandText = SQL;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
第二,是不是CON,CMD和DA妥善處理? 第二個有什麼問題嗎?
謝謝!
因爲它擁有物理數據庫資源,所以連接對象是關閉或處理最重要的對象。直到GC在第二種情況下確定對象時纔會關閉,如果有異常。處理命令和數據適配器是一個非常好的主意,但並不重要。 –