我试图将数据库中的用户名保存到一个变量中以便在另一个 QDialog 中使用,但是当我尝试在另一个对话框中使用它时该变量为空
qry.prepare("select nome from Users where email='"+user+"' and senha='"+password+"'");
if(qry.exec()) {
int count=0;
while(qry.next()) {
ui->label_2->setText(qry.value(0).toString());
count++;
}
if (count == 1) {
usuario = ui->label_2->text();
ui->errologin->setText("");
logado= true;
this->hide();
}
这就是我在另一个对话框中尝试调用它的方式:
ui->label->setText(log.usuario);
这是头文件中的变量声明:
public:
explicit login(QWidget *parent = nullptr);
~login();
bool logado;
QString usuario;
最佳答案
有一件事你可以做得更好,而不是这个:
qry.prepare("select nome from Users where email='"+user+"' and senha='"+password+"'");
替换为:
qry.prepare("select nome from users where email=? and senha=?");
qry.bindValue(0, user);
qry.bindValue(1, password);
请不要构建连接字符串的查询。
除此之外,无法判断您的错误在哪里,因为您没有按照@AlanBirtles 和@eyllanesc 的要求提供最小的可重现示例。我在您提供的代码中没有看到问题,它可能隐藏在您没有显示的代码中的某处。
另一个建议:尝试将您的问题减少到最小的测试程序可能会帮助您自己找到问题。例如,如果您怀疑您对 QSqlQuery 类的使用,那么将您的查询放在控制台程序中,看看它是否返回正确的结果。如果它仍然不能正常工作,那么将你的(完整的)测试程序发布到这里。
关于c++ - 将 SQLite 数据库中的数据保存到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59057245/