做了一个登录系统,可供管理员、教师、与学生三类人登录。
DBHelper部分代码如下:
public static DataTable GetDataTable(string sql, SqlParameter[] para)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
if (para != null)
{
cmd.Parameters.AddRange(para);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable temp = new DataTable();
da.Fill(temp);
cmd.Parameters.Clear();
connection.Close();
return temp;
}
管理员登录部分的代码如下(DAL层的):
public static bool CheckAdmin(ref Teacher admin)
{
string sql = "select * from Teacher where TeacherID=@id and TeacherPwd=@pwd and TeacherRole='管理员'";
SqlParameter[] para=new SqlParameter[]
{
new SqlParameter("@id",admin.TeacherID),
new SqlParameter("@pwd",admin.TeacherPwd),
};
DataTable temp=DBHelper.GetDataTable(sql,para);
if (temp.Rows.Count > 0)
{
Teacher t = new Teacher();
//t.TeacherID = temp.Rows[0]["TeacherID"].ToString();
t.TeacherName = temp.Rows[0]["TeacherName"].ToString();
t.Role = temp.Rows[0]["TeacherRole"].ToString();
admin = t;
return true;
}
else
{
admin = null;
return false;
}
}
然后教师登录部分的代码是仿照管理员部分的写的(DAL层的):
public static bool CheckTeacher(ref Teacher teacher)
{
string sql = "select * from Teacher where TeacherID=@id and TeacherPwd=@pwd and TeacherRole='教师'";
SqlParameter[] para = new SqlParameter[]
{
new SqlParameter("@id",teacher.TeacherID),
new SqlParameter("@pwd",teacher.TeacherPwd),
};
DataTable temp = DBHelper.GetDataTable(sql, para);
if (temp.Rows.Count > 0)
{
Teacher t = new Teacher();
t.TeacherName = temp.Rows[0]["TeacherName"].ToString();
t.Role = temp.Rows[0]["TeacherRole"].ToString();
teacher = t;
return true;
}
else
{
teacher = null;
return false;
}
}
但是只有管理员能登上去,用了断点调试后发现在教师登录部分的代码中:
DataTable temp = DBHelper.GetDataTable(sql, para);
if (temp.Rows.Count > 0)
得到的Count的值为0。调用的是同样的方法啊,为什么管理员代码部分获取的Count值就为1呢,百思不得其解。
------解决方案--------------------------------------------------------
查你的sql的执行结果
------解决方案--------------------------------------------------------
select * from Teacher where TeacherID=@id and TeacherPwd=@pwd and TeacherRole like'%教师%'
试试
检查“教师”前后是否有空白(空格)
------解决方案--------------------------------------------------------
调试下 把你的参数值放到SQL中 然后SQL语句到数据库中执行下 看能不能查出数据