/// <summary>
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <param name="connectionString">一个有效的数据库连接字符串</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>A SqlDataReader containing the results</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
// we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
#region//ExecuteDataSet方法
================================================================================================
- 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();
SqlDataReader myReader = 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 ,在创建连接的时候不能用using,正确的写法如下
public static SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand(strSQL, connection))
{
try
{
connection.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
}
}
加红字段:CommandBehavior.CloseConnection有何作用: