新しいsqlite3データベースファイルを初期化するために使用したいいくつかのSQLステートメントを含むファイルがあります。どうやら、 sqlite3は関数を介してではなく、関数を介して1つのクエリで複数のステートメントのみを処理し ます。それはすべて問題ありませんが、capiではなくQtSQLapiを直接使用したいと思います。QSqlQueryを介して同じ初期化ファイルをロードすると、sqlite3apiからprepare/step / finalize関数を直接使用するのと同じように、最初のステートメントのみが実行されます。ステートメントごとにquery.exec()を個別に呼び出すことなく、QSqlQueryで複数のクエリを実行する方法はありますか?sqlite3_exec()
prepare/step/finalize
12115 次
2 に答える
13
QSqlQuery :: prepare()およびQSqlQuery :: exec()のQtドキュメントで明確に述べられているように、
SQLiteの場合、クエリ文字列には一度に1つのステートメントしか含めることができません。複数のステートメントが指定されている場合、関数はfalseを返します。
この制限に対する唯一の既知の回避策は、すべてのsqlステートメントを文字列で区切って、ステートメントを分割し、それぞれをループで実行することです。
次のサンプルコードを参照してください(区切り文字として「;」を使用し、クエリ内で同じ文字が使用されていないことを前提としています。where/ insert / updateステートメントの文字列リテラルに特定の文字が含まれている可能性があるため、これには一般性がありません)。
QSqlDatabase database;
QSqlQuery query(database);
QFile scriptFile("/path/to/your/script.sql");
if (scriptFile.open(QIODevice::ReadOnly))
{
// The SQLite driver executes only a single (the first) query in the QSqlQuery
// if the script contains more queries, it needs to be splitted.
QStringList scriptQueries = QTextStream(&scriptFile).readAll().split(';');
foreach (QString queryTxt, scriptQueries)
{
if (queryTxt.trimmed().isEmpty()) {
continue;
}
if (!query.exec(queryTxt))
{
qFatal(QString("One of the query failed to execute."
" Error detail: " + query.lastError().text()).toLocal8Bit());
}
query.finish();
}
}
于 2012-01-30T11:12:36.340 に答える
1
ファイルからSQLを読み取り、一度に1つのステートメントで実行する簡単な関数を作成しました。
/**
* @brief executeQueriesFromFile Read each line from a .sql QFile
* (assumed to not have been opened before this function), and when ; is reached, execute
* the SQL gathered until then on the query object. Then do this until a COMMIT SQL
* statement is found. In other words, this function assumes each file is a single
* SQL transaction, ending with a COMMIT line.
*/
void executeQueriesFromFile(QFile *file, QSqlQuery *query)
{
while (!file->atEnd()){
QByteArray readLine="";
QString cleanedLine;
QString line="";
bool finished=false;
while(!finished){
readLine = file->readLine();
cleanedLine=readLine.trimmed();
// remove comments at end of line
QStringList strings=cleanedLine.split("--");
cleanedLine=strings.at(0);
// remove lines with only comment, and DROP lines
if(!cleanedLine.startsWith("--")
&& !cleanedLine.startsWith("DROP")
&& !cleanedLine.isEmpty()){
line+=cleanedLine;
}
if(cleanedLine.endsWith(";")){
break;
}
if(cleanedLine.startsWith("COMMIT")){
finished=true;
}
}
if(!line.isEmpty()){
query->exec(line);
}
if(!query->isActive()){
qDebug() << QSqlDatabase::drivers();
qDebug() << query->lastError();
qDebug() << "test executed query:"<< query->executedQuery();
qDebug() << "test last query:"<< query->lastQuery();
}
}
}
于 2013-10-06T11:53:46.730 に答える