我创建了带有连接到 SQL 数据库的 ID 和密码登录系统的学校项目。在学生中没有问题。但是当我尝试以老师身份登录时出现这样的错误:
** 参数化查询“(@p1 nvarchar(4000),@p2 nvarchar(4000))select * from teachers wh”需要未提供的参数“@p1”。**
public string ID, password;
private void teacherform_Load(object sender, EventArgs e) {
con.Open();
SqlCommand com = new SqlCommand("select * from teachers where t_id = @p1 and t_password=@p2", con);
com.Parameters.AddWithValue("@p1", ID);
com.Parameters.AddWithValue("@p2", password);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read()) {
teacherform tf = new teacherform();
tf.Show();
this.Hide();
}
else {
MessageBox.Show("ID or password incorrect!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
}
错误看起来像这样:
我想用密码和ID以教师身份登录
如果这些值中的任何一个是
null
,那么参数根本不会被传递。您需要将它与DBNull.Value
合并。
此外
using
.using
.ExecuteScalar
select *
,只需返回select 1
.AddWithValue
,将参数作为它们的确切类型传递,包括长度。private void teacherform_Load(object sender, EventArgs e)
{
const string query = @"
select 1
from teachers
where t_id = @id
and t_password = @passHash;
";
using var con = new SqlConnection(YourConnString);
using var com = new SqlCommand(query, con);
com.Parameters.Add("@id", SqlDbType.VarChar, 100).Value = ID ?? (object)DBNull.Value;
com.Parameters.Add("@passHash", SqlDbType.VarBinary, 128).Value = SaltAndHashPassword(ID, password) ?? (object)DBNull.Value;
con.Open();
var result = com.ExecuteScalar() == 1;
con.Close();
if(result)
{
teacherform tf = new teacherform();
tf.Show();
this.Hide();
}
else
{
MessageBox.Show("ID or password incorrect!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}