问题描述
“System.InvalidOperationException”类型的未经处理的异常在 System.Data.dll 中发生 ;
sqldatareader 在封装的sqlHelper里面能查询出数据,return到外面就报错了,hasRows报上面的错误
问题出现的环境背景及自己尝试过哪些方法
把sqlhelper 里面的链接数据库的代码,去掉using ,还是不行
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
//sqlhelper的方法这是
//查询信息的语句
public static SqlDataReader selectMes( string sqlstr,CommandType comtype ,params SqlParameter[] param) {
sqlstr = "select * from nameList where name='张三'";
SqlConnection con = new SqlConnection(constr);
using (SqlCommand com= new SqlCommand(sqlstr, con)) {
if (param!=null) {
com.Parameters.AddRange(param);
}
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
com.CommandType = comtype;
SqlDataReader res = com.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Student stu = null;
if (res.HasRows)
{
while (res.Read())
{
stu = new Student();
stu.id = res.GetInt32(0);
stu.name = res.GetString(1);
stu.num = res.GetString(2);
stu.gender = res.GetString(3);
}
}
return res;
}
finally {
con.Close();
con.Dispose();
}
}
//这是调用报错的地方
public Student loginDal2(string name) {
Student stu = null;
string sql = "select * from nameList where name='张三'";
SqlParameter[] param = {
new SqlParameter("@name",SqlDbType.NVarChar,50) {
Value=name
}
};
using (SqlDataReader res = sqlHelper.selectMes(sql,CommandType.Text)) {
if (res.HasRows)
{
while (res.Read())
{
stu = new Student();
stu.id = res.GetInt32(0);
stu.name = res.GetString(1);
stu.num = res.GetString(2);
stu.gender = res.GetString(3);
}
}
}
return stu;
}
解决了,我sqlhelper里面 finally{} 里面关闭了数据库链接;去掉这段就行了。