c#資料庫訪問返回值型別為SqlDataReader時使用using時注意的問題
在封裝通用 SQLSERVER 資料可訪問方法時,如果返回值型別為 SqlDataReader ,那麼在建立連線字串的時候,我們不能寫成如下
public static SqlDataReader ExecuteReader(string strSQL)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(strSQL, connection))
{
try
{
connection.Open();
SqlDataReadermyReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
}
}
}
你在使用using建立的時候,在SqlDataReader 賦值後return時,SqlConnection 就會被釋放資源,連線就會被關閉。而我們傳遞過去的SqlDataReader是引用型別,接收傳遞過去的SqlDataReader 的地方呼叫的時候,就會提示連線已經被關閉,無法呼叫,因為 using (SqlConnection connection = new SqlConnection(connectionString))在方法結束時,就把資源釋放了,並關閉了連線,為了正常接收傳遞過去的SqlDataReader
public static SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand(strSQL, connection))
{
try
{
connection.Open();
SqlDataReadermyReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
}
}