Qt SQL LIKE语句返回错误
Qt SQL LIKE Statement returning error
我一直在用这种方式执行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");
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- glad 导致 glfwSwapBuffers 返回错误消息
- 我的模板类方法返回错误类型?
- 共享内存:MapViewOfFile 返回错误 5
- 使用 std::forward_list 返回错误的队列实现
- FFMPEG:sws_scale返回错误:切片参数 0, 2160 无效
- __int64 CString 返回错误的值 - C++ MFC
- C++ OpenGL 中,绘制形状返回错误
- Python os.system() 返回错误值
- 函数从指针 c++ 中获取错误的值并返回错误的答案
- LibClang clang_getArgType() 返回错误的类型
- 除法函数返回错误的值
- 当命令失败时,gzip 会在 C++ 中返回错误代码吗?
- 矩阵逆变器返回错误的反转
- openCL-创建子缓冲区返回错误代码13
- Qt SQL LIKE语句返回错误
- GetLastError()从FtpPutFile()返回错误6
- PfCreateInterface返回错误120(未实现)
- 为什么 Pa_GetStreamTime() 返回错误?
- G++ 在尝试使用 G++ 使用 openCV 进行编译后返回错误