我在一個類中有兩個方法包含這些代碼,在GetDefinitionOfWord方法中,起初我一直調用GetDictionaryFilePath,它正確地返回DB的名字,但是在方法GetDefinitionOfWord中當execute db .setDatabaseName(GetDictionaryFilePath(ID));SQLDataBase setDatabaseName在QT中不起作用
它沒有設置數據庫名稱,無法打開數據庫,我會得到錯誤,我該如何解決這個問題?
請幫我
QString Dictionary_Operation::GetDefinitionOfWord(QString ID, QString Word)
{
QString Result = "";
QString FinalResult = "";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QString DBOpenErrorTitle = QString::fromStdString("Error");
QString DBOpenErrorMessage = QString::fromStdString("Access denied.");
QString FileName = GetDictionaryFilePath(ID);
db.setDatabaseName(GetDictionaryFilePath(ID));
if (QFile::exists(QString::fromStdString(".\\" + FileName.toStdString()))) {
db.setDatabaseName(GetDictionaryFilePath(ID));
if (!db.open()) {
QMessageBox::critical(0, DBOpenErrorTitle, DBOpenErrorMessage,
QMessageBox::Cancel);
}
else
{
QSqlQuery query;
query.exec(QString::fromStdString("PRAGMA encoding = UTF-16"));
QString s = QString::fromStdString("SELECT Definition FROM Dictionary_Words WHERE HeadWord = '%1'").arg(ID);
QSqlQuery sql(s, db);
while (sql.next())
{
Result = Result.append(sql.record().value(0).toString());
}
db.close();
FinalResult = ReplaceImageToBase64(Result, ID);
}
}
QSqlDatabase::removeDatabase(FileName);
return FinalResult;
}
和其他方法是:
QString Dictionary_Operation::GetDictionaryFilePath(QString ID)
{
QString Result = "0";
QSqlDatabase dbGetDictionaryFilePath = QSqlDatabase::addDatabase("QSQLITE");
QString DBOpenErrorTitle = QString::fromStdString("Error");
QString DBOpenErrorMessage = QString::fromStdString("Access denied.");
if (QFile::exists(".\\1.pldb")) {
dbGetDictionaryFilePath.setDatabaseName(QString::fromStdString("1.pldb"));
if (!dbGetDictionaryFilePath.open()) {
QMessageBox::critical(0, DBOpenErrorTitle, DBOpenErrorMessage,
QMessageBox::Cancel);
}
else
{
QSqlQuery query;
query.exec(QString::fromStdString("PRAGMA encoding = UTF-16"));
QString s = QString::fromStdString("SELECT FileName FROM Dictionaries WHERE ID = %1").arg(ID);
QSqlQuery sql(s, dbGetDictionaryFilePath);
while (sql.next())
{
Result = sql.record().value(0).toString();
}
// dbGetDictionaryFilePath.close();
}
}
QSqlDatabase::removeDatabase(QString::fromStdString("1.pldb"));
return Result;
}