MySQL密码登录代码
本文关键字:代码 登录 密码 MySQL | 更新日期: 2023-09-27 18:16:49
我正在尝试用MySQL在C#中编写登录代码。基本上,用户输入用户名和密码,然后代码检查数据库密码是否正确。我在从数据库中读取代码时遇到问题。。。这就是我现在的位置。
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();
根据我过去所做的,我认为这会奏效,但如果我把它打印出来,它似乎没有被阅读。我还是MySQL的新手,所以任何帮助都会很棒。
非数字字段值必须用单引号括起来。
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
但是必须使用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();
正如AVD所说,您应该使用参数来防止sql注入。。。。