Qt SQL LIKE语句返回错误

Qt SQL LIKE Statement returning error

本文关键字:返回 错误 语句 LIKE SQL Qt      更新时间:2023-10-16

我一直在用这种方式执行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();
}

此时您可能已经解决了问题,但以下是我的解决方案:

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);

试试这个

search = "%"+search+"%";
query.prepare("select ID,Name from BOOKS where ((Name LIKE :search) or (ID LIKE :search)) where UserName=:user");