嗨,我正在尝试创建一个登录表单,我正在使用SQLite和Qt。与数据库的连接成功,query.prepare((和query.exec((都返回true。但是,无论我做什么,qry.next((都总是返回false。query.lastError((返回类似QSqlError的错误(",","(。我尝试了许多类似讨论中建议的解决方案,但都无济于事,我不明白错误的性质以及该怎么办
QString username = ui->username->text();
QString password = ui->password->text();
QSqlQuery query(mydb);
QString qryString = QString("SELECT * FROM users WHERE username = :username AND password = :password");
query.prepare(qryString); //returns true
query.bindValue(":username", username);
query.bindValue(":password", password);
query.exec(); //also ok
if(!query.next())
{
qDebug() << query.lastError();
}
else
{
qDebug() << "Success!";
}
/* while(query.next())
{
QString usernameFromDB = query.value(1).toString();
QString passwordFromDB = query.value(2).toString();
if(usernameFromDB == username && passwordFromDB == password)
{
QMessageBox::information(this, "Success", "Login success");
}
else
{
QMessageBox::information(this, "Failed", "Login failed 2");
}
}*/
您需要通过添加查询来初始化查询。第一个如下:
QString username = ui->username->text();
QString password = ui->password->text();
QSqlQuery query(mydb);
QString qryString = QString("SELECT * FROM users WHERE username = :username AND password = :password");
query.prepare(qryString); //returns true
query.bindValue(":username", username);
query.bindValue(":password", password);
query.exec(); //also ok
query.first(); //add this line
if(!query.next())
{
qDebug() << query.lastError();
}
else
{
qDebug() << "Success!";
}
/* while(query.next())
{
QString usernameFromDB = query.value(1).toString();
QString passwordFromDB = query.value(2).toString();
if(usernameFromDB == username && passwordFromDB == password)
{
QMessageBox::information(this, "Success", "Login success");
}
else
{
QMessageBox::information(this, "Failed", "Login failed 2");
}
}*/