我最近开始与QT合作,但遇到了一个小问题。我似乎无法理解QVariant的工作方式。我一直在浏览帮助并在线寻找信息,但是并没有陷入。在我的项目中,我试图用数据库中的制造商列表填充组合框。我已经打开数据库并取出条目,但是我将它们全部重命名为manValue。现在我了解了为什么会这样,问题是我不了解如何正确使用QVariant来获得所需的结果。最初,我认为“manValue”将是保存数据库中实际值的字符串的标识符,但相反,它会从数据库中读取该值并确保其不为null,然后重命名。在为QVariant分配任何属性并将其从数据库接收的文本分配给它之前,我已经尝试过创建一个字符串,然后在manValue仍然没有运气的地方插入该字符串。任何帮助将不胜感激。抱歉,我知道这很简单,我只是菜鸟,而帮助文档经常使我感到困惑。
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setHostName("LOCALHOST\\TestERPServer");
db.setDatabaseName("TestERPConnection");
if (db.open())
{
QMessageBox::information(this,"Connected","Connection to the Database was Established\n"
"\nStatus: Connected");
QSqlQuery mfrQry;
if (mfrQry.exec("SELECT * FROM erp_data.manufacturers;"))
{
if (mfrQry.value(1) == "")
{
QMessageBox::information(this,"No Connection","Nothing in the Manufacturer Database\n"
"\nError: " + db.lastError().text());
}
else
{
while (mfrQry.next())
{
ui->mfrComboBox->addItem("manValue",QVariant(mfrQry.value(1)));
}
}
}
else
{
QMessageBox::information(this,"No Connection","Connection to the Manufacturer Database could not be Established\n"
"\nError: " + db.lastError().text());
}
}
else
{
QMessageBox::information(this,"No Connection","Connection to the Database could not be Established\n"
"\nError: " + db.lastError().text());
}
最佳答案
提供的代码中的第一个问题与您操纵 QSqlQuery
的方式有关。
为了移至有效记录,您必须使用以下之一:
next()
previous()
first()
last()
seek()
在有效记录上后,必须使用
value()
函数才能获取所需的列。返回的值为 QVariant
,因此您需要使用toSomething
提供的许多QVariant
函数之一将其转换为所需的类型。因此,在您的情况下,代码应如下所示:
QSqlQuery mfrQry;
if (mfrQry.exec("SELECT * FROM erp_data.manufacturers;"))
{
// This will loop through all records returned by the query
while (mfrQry.next()) {
// mfrQry.value(COLID) returns a QVariant containing the data of the current
// record in column COLID.
// Using toString we convert it to String
QString stringValue = mfrQry.value(COLID).toString();
// Now handle the QString the way you want...
}
}
关于c++ - 从数据库提取数据时使用QVariant的正确方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9794665/