简体   繁体   中英

MySQL Password Login Code?

I'm trying to do a Login code in C# with MySQL. 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.

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 .

 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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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