简体   繁体   English

MySQL密码登录代码?

[英]MySQL Password Login Code?

I'm trying to do a Login code in C# with MySQL. 我正在尝试使用MySQL在C#中执行登录代码。 Basically the user enters a username and password then the code checks the database if the the password is correct. 基本上,用户输入用户名和密码,然后代码检查密码是否正确。 I'm having trouble getting the code to read from the data base... Here is where I'm at. 我无法从数据库读取代码...这就是我的位置。

public string strUsername;
public string strPassword;


//Connect to DataBase
MySQLServer.Open();

//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
  string TruePass = mySQLReader.GetString(1);
  if (strPassword == TruePass)
  {
    blnCorrect = true;
    //Get Player Data
  }
}

MySQLServer.Close();

From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. 从我过去所做的事情来看,我认为这会起作用,但是如果我将其打印出来,看起来好像它没有被阅读。 I am still fairly new to MySQL so any help would be Great. 我对MySQL还是很陌生,所以任何帮助都会很棒。

Non-numeric field value must be enclosed with single quote. 非数字字段值必须用单引号引起来。

mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer; 

but you have to use Parameters to prevent SQL Injection . 但是您必须使用Parameters来防止SQL注入

 mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =@username"; 
 mySQLCommand.Connection=MySQLServer;
 mySQLCommand.Parameters.AddWithValue("@username",strUsername);
        string con_string = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
        string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
        SqlConnection Con = new SqlConnection(con_string);
        SqlCommand Com = new SqlCommand(query, Con);
        Con.Open();
        SqlDataReader Reader;
        Reader = Com.ExecuteReader();

        if (Reader.Read())
        {
            lblStatus.Text="Successfully Login";
        }
        else
        {
           lblStatus.Text="UserName or Password error";
        }
        Con.Close();

As AVD said you should use parameters to prevent sql injection.... 正如AVD所说,您应该使用参数来防止SQL注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM