我想创建一个登录系统,我有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");
}
}
答案 0 :(得分:0)
已更新
查询中存在错误 (有时您需要在Qt的其他环境(例如 mysql clis )或在线环境中调试查询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");
}
}