当我使用下面的代码时,如果用户名和密码相同,它工作正常,如果我提供了错误的用户名和密码,它会给我留言或登录:
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = Helper.getconnection();
con.Open();
SqlCommand cmd = new SqlCommand("select SupportName, Password from Logins where SupportName='" + txtSupportName.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
string Name = txtSupportName.Text;
string Pwd = txtPassword.Text;
while (dr.Read())
{
if ((dr["SupportName"].ToString() == Name) && (dr["Password"].ToString() == Pwd))
{
// MessageBox.Show("welcome");
Form Support = new Support();
Support.ShowDialog();
}
else
{
MessageBox.Show("SupportName and password are invalid");
}
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (txtSupportName.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Support Name!");
txtSupportName.Focus();
return;
}
if (txtPassword.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Description!");
txtPassword.Focus();
return;
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码似乎存在一些问题:
您应该在运行查询之前验证输入
您应该参数化您的查询(SO上有大量样本)而不是使用字符串连接
您似乎假设您将从SQL查询中获得结果.您应该检查dr.HasRows详细信息是否正确,或检查是否dr.Read()返回true以确定是否显示消息框
您应该使用using块处理数据库对象.例如(不确定为什么格式化不起作用):
使用(SqlConnection con = Helper.getconnection()){...}
而不是调用Dispose和Close明确.即使您确实想要明确调用Dispose,Close也应该在finally块中进行调用.
| 归档时间: |
|
| 查看次数: |
1258 次 |
| 最近记录: |