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;
}
}
{
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;
}
}
因为是返回一个连接,所以不能断开。
CommandBehavior.CloseConnection
表求 SqlDataReader 关闭时连接也会关闭。
所以这要用户关闭rdr就可以了。
正解CommandBehavior.CloseConnection
CloseConnection 在执行该命令时,如果关闭关联的 DataReader 对象,则关联的 Connection 对象也将关闭。
代码设置了CommandBehavior.CloseConnection
你在调用该方法后 记得 关闭Reader就可以关闭SqlConnection了。
好像是提示连接已关闭,CommandBehavior.CloseConnection表示连接随reader关闭而关闭
当你使用完DR,DR就自动关闭
rdr 关闭后 连接就关闭了
但是
个人 觉得
最好是 把 conn 的打开和关闭 显示再 使用函数的外面声明