public SqlDataReader Getgrxx(int userID)
{ ///获取连接字符串
string connectionString = ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString;
///创建连接
SqlConnection con = new SqlConnection(connectionString);
///创建SQL语句
string cmdText = "SELECT * FROM tg_gr WHERE grid=@UserID";
///创建SqlCommand
SqlCommand cmd = new SqlCommand(cmdText, con);
///创建参数并赋值
cmd.Parameters.Add("@UserID", SqlDbType.Int, 4);
cmd.Parameters[0].Value = userID;
///定义SqlDataReader
SqlDataReader dr;
try
{ ///打开连接
con.Open();
///读取数据
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{ ///抛出异常
throw new Exception(ex.Message, ex);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose(); } } return dr;
}
我加入finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose(); } }
提示错误:阅读器关闭时 Read 的尝试无效。
如果我不加入最好关闭仅仅是 dr.Close();
dr.Dispose();没有关闭con
{ ///获取连接字符串
string connectionString = ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString;
///创建连接
SqlConnection con = new SqlConnection(connectionString);
///创建SQL语句
string cmdText = "SELECT * FROM tg_gr WHERE grid=@UserID";
///创建SqlCommand
SqlCommand cmd = new SqlCommand(cmdText, con);
///创建参数并赋值
cmd.Parameters.Add("@UserID", SqlDbType.Int, 4);
cmd.Parameters[0].Value = userID;
///定义SqlDataReader
SqlDataReader dr;
try
{ ///打开连接
con.Open();
///读取数据
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{ ///抛出异常
throw new Exception(ex.Message, ex);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose(); } } return dr;
}
我加入finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose(); } }
提示错误:阅读器关闭时 Read 的尝试无效。
如果我不加入最好关闭仅仅是 dr.Close();
dr.Dispose();没有关闭con
dr.Dispose(); 不是最好是最后
con.Dispose(); 这不是关闭了的吗???
你调用Getgrxx方法返回的那个reader用完后关闭就行了如:SqlDataReader dr = Getgrxx(xx);dr用完后dr.close();