我一直在使用这种方式执行SQL查询,但是对于LIKE来说,它不起作用,我不知道为什么。任何想法?错误消息显示QSqlError(“”,“参数计数不匹配”,“”)。谢谢。
void MainWindow::on_searcButton_clicked()
{
Login user;
dbConnect db;
if (!db.dbOpen()){
qDebug()<<"DB not found";
}
QSqlQuery query;
QString search=ui->searchEdit->text();
qDebug()<<"Search: "<<search;
query.prepare("select ID,Name from BOOKS where ((Name LIKE :search%) or (ID LIKE :search%)) where UserName=:user;");
query.bindValue(":search",search);
query.bindValue(":user",user.userLogOn);
if(!query.exec()){
qDebug()<<"Query error: "<<query.lastError();
}
QSqlQueryModel *modal =new QSqlQueryModel();
modal->setQuery(query);
qDebug()<<modal->rowCount();
ui->bookList->setModel(modal);
//db.dbClose();
}
答案 0 :(得分:2)
这时候您可能已经解决了问题,但这是我的解决方案:
QSqlQuery query;
query.prepare(QString("SELECT field1, field2, field3 "
"FROM table1 "
"WHERE %1 LIKE :search_string ").arg(someComboBox->currentText()));
// With QString::arg() you could use a combobox to select the field
// or any widget that you prefer.
// You can also use ILIKE Postgresql sentence for case insensitive
// Note that QSqlQuery::bindValue() is only for incoming values, not for replace fields,
// that's the reason why you need to use QString::arg() to replace the search field.
query.bindValue(":search_string", ("%" + searchLineEdit->text() + "%"));
// No need to use the SQL single quotes at the sides of percentage character ('%string%')
// This portion of code is useful to debug your query.
if(!query.exec()) {
qDebug() << "Error in query, it happened: " + query.lastError().text();
qDebug() << "The SQL text was: " << query.lastQuery().toUtf8;
}
// And if you need to watch your bound values, use this:
qDebug() << queryForModel.boundValue(0).toString();
// Here's a bonus to see the results.
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(query);
someTableView->setModel(model);
答案 1 :(得分:0)
尝试一下
search = "%"+search+"%";
query.prepare("select ID,Name from BOOKS where ((Name LIKE :search) or (ID LIKE :search)) where UserName=:user");