C# 如何知道查询是否正确
我正在使用dapper library制作一个登录表单。这里有问题,即使密码或用户名错误,我也无法使其正常工作。它会打开一个新表单C# 如何知道查询是否正确,c#,dapper,C#,Dapper,我正在使用dapper library制作一个登录表单。这里有问题,即使密码或用户名错误,我也无法使其正常工作。它会打开一个新表单 if (string.IsNullOrEmpty(txtUsername.Text)) { MessageBox.Show("Please enter your usernmae.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (string.IsNullOrEmpty(txtUsername.Text))
{
MessageBox.Show("Please enter your usernmae.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtUsername.Focus();
return;
}
try
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
var data = db.Query("select Username,Password from UserLog", commandType: CommandType.Text);
if ((data.SingleOrDefault() !=null)
{
MessageBox.Show("You have been succesfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
FormHome frm= new FormHome();
frm.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Your Username or Password is Incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
您只需将此查询发送到数据库,因此无论登录信息如何,它每次都会返回结果:
select Username, Password from UserLog
因此,它当然会通过,因为您没有过滤记录。只要数据库中有1条记录,它就会通过
您需要发送用户登录信息,并检查是否存在记录,其中包含您尝试验证的当前用户的登录信息:
IEnumerable users = db
.Query("select Username, Password from UserLog where UserName = @UserName and Password = @Password",
new {UserName = txtUsername.Text, Password = // put the password here});
if (users.Any())
{
// authenticated so do whatever
}
看看数据内容,为什么是data.SingleOrDefault=空总是真的。