有空的都进来看下修改别人的系统
public static SchoolRecord GetSchoolRecordById(int id)
{
string sql = "select * from Job_SchoolRecord where id="+id;
SqlParameter[] para = new SqlParameter[]
{
new SqlParameter("@id",id)
};
SqlDataReader reader = DBHelper.ExecuteDataReader(sql, para);
if (reader.Read())
{
SchoolRecord sr = new SchoolRecord();
sr.Id = (int)reader["Id"];
sr.Name = (string)reader["Name"];
reader.Close();
return sr;
}
return null;
}
当 reader没有数据时报错
未将对象引用设置到对象的实例如何判断reader 有数据呢 。if(reader.hasRows)是这个属性吧。
string sql = "select * from Job_SchoolRecord where id="+id
上面的语句是我改的。下面是网上系统下的原来的语句。哪个对呢。两个都可以运行
string sql = "select * from Job_SchoolRecord where id=@id"
不知点解点搜索功能的时候点几次就会未将对象引用设置到对象的实例
public static SqlDataReader ExecuteDataReader(string sql)
{
return ExecuteDataReader(sql, null, CommandType.Text);
}
public static SqlDataReader ExecuteDataReader(string sql, SqlParameter[] paras, CommandType type)
{
SqlDataReader dr = null;
//构造连接对象
SqlConnection con = new SqlConnection(str);
//构造执行对象
SqlCommand cmd = GetCommand(sql, paras, type);
cmd.Connection = con;
try
{
//打开连接
con.Open();
//执行命令
dr = cmd.ExecuteReader();
}
catch (Exception ex)
{
//输出异常
Console.WriteLine(ex.Message);
}
return dr;
}
public static SqlCommand GetCommand(string sql, SqlParameter[] paras, CommandType type)
{
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = type;
if (paras != null)
{
cmd.Parameters.AddRange(paras);
}
return cmd;
}
------解决方案--------------------if(!reader.next())
------解决方案--------------------你的sql用错了id="+id;这个id不是参数,这是个字符串拼接,@id,这个才是参数,如果是id拼接的话,就不该要SqlParameter