我有一个简单的登录屏幕,当用户单击登录按钮时,应该运行 sql 查询来搜索用户名 == 用户名文本框和密码 == 密码文本框的行。我的代码的这一部分工作正常。
但是,当我尝试运行 if 语句时,它将打开一个新表单并关闭登录表单,它会出错,即使我添加了一些消息框来检查语句刺比较是否正确。
有任何想法吗?
登录按钮:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username='" + userText + "' and Password='" + passText + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
MessageBox.Show(userText + " / " + dr["Username"].ToString());
MessageBox.Show(passText + " / " + dr["Password"].ToString());
if (dr["Username"].ToString() == userText && dr["Password"].ToString() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
dr.Close();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
登录尝试:
根据从下面的答案和评论中获取的建议,代码已更正为以下内容(在 sql 命令中使用 sql 参数):
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username = @username and Password = @password", cn);
cmd.Parameters.Add(new SqlParameter("username", userText));
cmd.Parameters.Add(new SqlParameter("password", passText));
SqlDataReader dr = cmd.ExecuteReader();
try
{
dr.Read();
if (dr["Username"].ToString().Trim() == userText && dr["Password"].ToString().Trim() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
}
catch
{
MessageBox.Show("Invalid Username or Password");
}
dr.Close();
cn.Close();
}