对于问题的任何明显重叠提前抱歉,但我已经搜索了本网站上每个可能的问题,以找到我的问题的答案,但没有一个有效。主要问题是我似乎无法打开我的SQLITE3数据库以便搜索它并显示到QTableView。我的代码如下:
void MainWindow::on_searchBButton_clicked() {
qDebug() << QSqlDatabase::drivers();
//Setup the search query and open database
//toolboxData = QSqlDatabase::addDatabase("QSQLITE");
//toolboxData.setDatabaseName(":/Resources/Resources/ToolSearch.db");
QString searchStr;
searchStr = ui->basicSearchInput->text();
//Filter out any hyphens
for (int i = 0; i < searchStr.length(); ++i) {
if (searchStr[i] == QLatin1Char('-')) searchStr[i] = QLatin1Char(' ');
}
//Do the actual searching now
QString sQry;
QSqlQueryModel *model = new QSqlQueryModel();
QSqlDatabase toolboxDb = QSqlDatabase::addDatabase("QSQLITE");
//toolboxDb.setDatabaseName(":/Resources/Resources/ToolSearch.db");
toolboxDb.setDatabaseName("C:\\New folder\\ToolSearch.db");
bool db_ok = toolboxDb.open();
if (!QFile::exists("C:\\New folder\\ToolSearch.db"))
qDebug() << "This file does not exist";
if (!db_ok)
qDebug() << "Connection Failed\n";
QSqlQuery *qry = new QSqlQuery(toolboxDb);
sQry += "SELECT * FROM ToolSearch WHERE keywords MATCH :searchTerm UNION SELECT * FROM ToolSearch WHERE name MATCH :searchTerm UNION ";
sQry += "SELECT * FROM ToolSearch WHERE category MATCH :searchTerm UNION SELECT * FROM ToolSearch WHERE subcategory MATCH :searchTerm ";
sQry += "UNION SELECT * FROM ToolSearch WHERE sources MATCH :searchTerm UNION SELECT * FROM ToolSearch WHERE usagetype :searchTerm UNION ";
sQry += "SELECT * FROM ToolSearch WHERE cost MATCH :searchTerm";
qry->prepare(sQry);
//Add the necessary single quotes to the given string
searchStr = '\'' + searchStr + '\'';
qry->bindValue(":searchTerm", searchStr);
qry->exec();
model->setQuery(*qry);
ui->searchResults->setModel(model);
ui->searchResults->show(); }
我在这里看到的大部分答案都表示要打开数据库,你必须按照以下方式写一些内容:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:\\SomeFolder\\SomeFile.db");
bool db_ok = db.open();
但是,我的几乎完全相同的代码用于打开数据库,甚至用绝对地址测试它,而不是我用“:/ Resources/Resources/ToolSearch.db”行的相对地址。此外,qDebug()的输出&lt;&lt; QSqlDatabase :: drivers()给出:
(“QSQLITE”,“QMYSQL”,“QMYSQL3”,“QODBC”,“QODBC3”,“QPSQL”,“QPSQL7”)
最后,我还使用了验证文件确实存在于我尝试使用if(!QFile :: exists())语句打开它的位置。所以,我不知道为什么这不起作用。我尝试运行此代码时收到的特定错误消息是“QSqlQuery :: prepare:database not open”。
非常感谢任何帮助!