我想在qt中制作应用程序,其中将是登录和注册系统,登录名和密码都在MySQL数据库中。我已经将数据库连接到我的应用程序,但我不知道如何将登录名和密码与"行编辑"中给出的进行比较,这是教程中的代码,但它是SQLite的教程
void login::on_pushButton_sign_in_clicked()
QString login, password;
login = ui->lineEdit_login_login->text();
password = ui->lineEdit_password_login->text();
QSqlQuery qry;
if(qry.exec("select logins, passwords * from users where logins = '" + login + "' and password = '" + password + "' " ))
{
while(qry.next())
{
hide();
mainwindow = new MainWindow(this);
mainwindow->show();
}
}
}
正如评论中提到的,您应该首先了解基本的SQL查询。假设您有一个users
表,它包含如下列:
| userId | name | username | password |
从自定义 AppmyUsername
和myPassword
后,SQL 查询可能如下所示:
SELECT userID, name from users WHERE username = 'myUsername' AND password = 'myPassword'
现在,您可以在代码中使用它:
void login::on_pushButton_sign_in_clicked()
{
QString username = ui->lineEdit_login_login->text();
QString password = ui->lineEdit_password_login->text();
QSqlQuery query;
query.prepare("SELECT userID, name from users WHERE
username = :username AND
password = :password");
query.bindValue(":username", username);
query.bindValue(":password", password);
if (query.exec())
{
if (query.size() > 0)
{
// You login a user here
QString name = query.value(1).toString();
qDebug() << name << "is logged in";
}
else
{
qDebug() << "Login failed. Invalid username or password.";
}
}
}
请注意,我认为这是出于学习目的。建议存储密码哈希而不是纯文本。干杯!