如果用户名和密码正确,我需要打开一个新表单,但我无法使用此代码,如果我输入正确的用户名或密码,它什么都不做。
private void login_Click(object sender, EventArgs e)
{
try
{
string connection = @"Data Source=DX-PC;Initial Catalog=login;Integrated Security=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = user.Text;
string passText = pass.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM log 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)
{
MessageBox.Show("This message won't Display");
}
}
catch
{
MessageBox.Show("Invalid Username or Password");
}
dr.Close();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:1)
我认为问题出在:
if (dr["Username"].ToString().Trim() == userText && dr["Password"].ToString().Trim() == passText)
{
MessageBox.Show("This message won't Display");
}
您的代码部分。尝试按如下方式添加其他内容:
if (dr["Username"].ToString().Trim() == userText && dr["Password"].ToString().Trim() == passText)
{
MessageBox.Show("This message won't Display");
} else {
MessageBox.Show(string.Format("{0}!={1}, {2}!={3}"
,dr["Username"].ToString().Trim(),userText,
dr["Password"].ToString().Trim(),passText
);
}
你可能会发现你的问题。
答案 1 :(得分:0)
试用此代码
cn.open
MySqlDataAdapter LoginAdapter = new MySqlDataAdapter();
dynamic CommandQuerry = @"SELECT * From users WHERE Username='" + UsernameField.Text + "'AND Password='" + PasswordField.Text + "';";
MySqlCommand LoginCommand = new MySqlCommand(); //The Login Command
MySqlDataReader LoginDataReader = default(MySqlDataReader); //Create a reader variable to check login details.
if (cn.State == ConnectionState.Open)
{
LoginCommand.Connection = SelectedSchoolDB;
LoginCommand.CommandText = CommandQuerry;
LoginAdapter.SelectCommand = LoginCommand;
LoginDataReader = LoginCommand.ExecuteReader();
if (Convert.ToInt32(LoginDataReader.HasRows) == 0)
{
DialogResult a = MessageBox.Show(@"Invalid username/password, please try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
LoginDataReader.Close(); // Close The reader
This.FormName.Hide(); //Close the login form
Newform.ShowDialog(); //Show the new form
}
cn.close()
}
希望此代码有助于:)
答案 2 :(得分:0)
虽然您提供的代码容易受到SQL注入和攻击。 XSS,但为了回答你的问题,SQL查询中过滤条件的字符串comaprision不区分大小写,而上面的.NET代码区分大小写。