当我从comboBox
中选择图书ID时,我想将图书名称的值加载到文本框中。首先,我编写了用于将Book Ids从数据库加载到comboBox
的代码,并且它完全加载了。这是方法。
void FictionSection::loadComboVal()
{
DatabaseConnection mydb;
QSqlQueryModel *modl = new QSqlQueryModel();
dbConOpen();
QSqlQuery *query = new QSqlQuery(mydb.db) ;
query->prepare(" select material_id from fiction ");
bool flag = query->exec();
//assigning the values to a QTableView
if(flag == true)
{
modl->setQuery(*query);
ui->cmbxId->setModel(modl);
}
mydb.dbConClose();
}
然后,一旦从textBox
中选择了书籍ID,我就编写了将值分配给comboBox
的代码。这是代码段:
// loading book names once user select the book id from combo box
void FictionSection::on_cmbxId_currentIndexChanged(int index)
{
QString value = ui->cmbxId->currentText();
int id;
if(!value.isEmpty())
{
id = value.toInt();
}
//Loading book table values to a table
dbC onOpen();
QSqlQuery query ;
QString ids = QString("values('") + QString::number(id);
query.prepare(" select material_title from book where material_id = '"+ids+"'");
bool flag = query.exec();
//assigning the values to a QTableView
if(flag == true)
{
ui->lneditFicNme->setText(query.value(1).toString());
}
dbConClose();
}
但是后来加载到comboBox
的值是不可见的,我无法像我预期的那样获得文本框的任何值。但没有编译或运行时错误。 Book Id在数据库中以int {book}的形式存储为varchar
。
我更改了代码如下:
void FictionSection::on_cmbxId_currentIndexChanged(int index)
{
QString value = ui->cmbxId->currentText();
int id;
if(!value.isEmpty())
{
id = value.toInt();
}
//Loading book table values to a table
dbConOpen();
QSqlQuery query ;
// QString ids = QString("values('") + QString::number(id);
query.prepare(" select material_title from book where material_id = ?");
query.bindValue(0,id);
bool flag = query.exec();
//assigning the values to a QTableView
if(flag == true)
{
ui->lneditFicNme->setText(query.value(1).toString());
}
else
{
QMessageBox :: critical(this,"Error",query.lastError().text());
}
dbConClose();
}
然后它给出如下错误:
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlQuery::value: not positioned on a valid record
QSqlQuery::value: not positioned on a valid record
我编辑了上面的代码,但仍然无法得到预期的结果。
void FictionSection::on_cmbxId_currentIndexChanged(int index)
{
DatabaseConnection con;
con.dbConOpen();
QString value = ui->cmbxId->currentText();
int id;
if(!value.isEmpty())
{
id = value.toInt();
}
//Loading book table values to a table
QSqlQuery query ;
// QString ids = QString("values('") + QString::number(id);
query.prepare(" select material_title from book where material_id = :id");
query.bindValue(":id",id);
bool flag = query.exec();
//assigning the values to a QTableView
if(flag == true)
{
while(query.next())
{
ui->lneditFicNme->setText(query.value(1).toString());
}
}
else
{
QMessageBox :: critical(this,"Error",query.lastError().text());
}
con.dbConClose();
}
请帮我解决这个问题。提前谢谢
答案 0 :(得分:0)
尝试使用QSqlQuery::next()
方法定位有效记录。