qt5从mysql数据库中选择数据

nfs0ujit  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(505)

我想做一个登录系统,我有mysql数据库,我想根据我的mysql数据库用户名和密码登录,但它不工作,我想我有问题,我的代码请检查代码

void MainWindow::on_loginBtn_clicked()
{

    QSqlDatabase db;

    db = QSqlDatabase::addDatabase("QMYSQL", "MyConnect");
    db.setHostName("localhost");
    db.setUserName("root");
    db.setPassword("");
    db.setDatabaseName("qtregister");

    QString username = ui->loginEdit->text();
    QString password = ui->loginPassword->text();

    if(db.open()) {

        QSqlQuery query(QSqlDatabase::database("MyConnect"));

        query.prepare(QString("SELECT username and password from users where username = :username AND password = :password"));
        query.bindValue(":username", username);
        query.bindValue(":password", password);

        if(!query.exec()) {
            QMessageBox::information(this, "Failed", "Failed To Login");

        }else {
          QMessageBox::information(this, "Success", "Login Success");
        }
    }
    else {
        QMessageBox::information(this, "Not Connected", "Not Conneced Success");
    }
}
piok6c0g

piok6c0g1#

更新
您的查询中有一个错误(有时您需要在另一个类似mysql clis或online的环境中调试您的查询)http://sqlfiddle.com)

SELECT username,password from users where username = :username AND password = :password

而不是

SELECT username and password from users where username = :username AND password = :password

更正的答案

void MainWindow::on_loginBtn_clicked() {

  QSqlDatabase db;

  db = QSqlDatabase::addDatabase("QMYSQL", "MyConnect");
  db.setHostName("localhost");
  db.setUserName("root");
  db.setPassword("");
  db.setDatabaseName("qtregister");

  QString username = ui - > loginEdit - > text();
  QString password = ui - > loginPassword - > text();

  if (db.open()) {

    QSqlQuery query(db);

    query.prepare(QString("SELECT username , password from users where username = :username AND password = :password"));
    query.bindValue(":username", username);
    query.bindValue(":password", password);

    if (!query.exec()) {
      QMessageBox::information(this, "Failed", "Error in executing query");

    } else {
      while (query.next()) {
        QString usernameFromDB = query.value(0).toString();
        QString passwordFromDB = query.value(1).toString();
        qDebug() << usernameFromDB << passwordFromDB;
        if (usernameFromDB == username && passwordFromDB == password)
          QMessageBox::information(this, "Success", "Login Success");
        else
          QMessageBox::information(this, "Failed", "Username or password error");
      }
    }
  } else {
    QMessageBox::information(this, "Not Connected", "Not Conneced Success");
  }
}

相关问题