#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlTableModel>
#include <QStringList>
#include <QSqlQuery>
#include <QTreeView>
#include <QFile>
#include <QSqlError>
{
return 0;
int successCount = 0;
foreach(const QString& statement, sqlStatements)
{
if (statement.trimmed() != "")
{
if (query.exec(statement))
successCount++;
else
qDebug() << "Failed:" << statement << "\nReason:" << query.lastError();
}
}
return successCount;
}
int main(int argc, char * argv[])
{
db.setDatabaseName(":memory:");
db.open();
ExecuteSqlScriptFile(db, "sql.sql");
tbl.setTable("table2");
tbl.select();
tv.setModel(&tbl);
tv.show();
return a.exec();
}
#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlTableModel>
#include <QStringList>
#include <QSqlQuery>
#include <QTreeView>
#include <QFile>
#include <QSqlError>
int ExecuteSqlScriptFile(QSqlDatabase & db, const QString & fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return 0;
QTextStream in(&file);
QString sql = in.readAll();
QStringList sqlStatements = sql.split(';', QString::SkipEmptyParts);
int successCount = 0;
foreach(const QString& statement, sqlStatements)
{
if (statement.trimmed() != "")
{
QSqlQuery query(db);
if (query.exec(statement))
successCount++;
else
qDebug() << "Failed:" << statement << "\nReason:" << query.lastError();
}
}
return successCount;
}
int main(int argc, char * argv[])
{
QApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open();
ExecuteSqlScriptFile(db, "sql.sql");
QSqlTableModel tbl(0, db);
tbl.setTable("table2");
tbl.select();
QTreeView tv;
tv.setModel(&tbl);
tv.show();
return a.exec();
}
To copy to clipboard, switch view to plain text mode
Tested with this script:
CREATE TABLE `table1` (
`id` INTEGER,
`bla1` TEXT,
PRIMARY KEY(`id`)
);
CREATE TABLE `table2` (
`id` INTEGER,
`bla2` TEXT,
PRIMARY KEY(`id`)
);
INSERT INTO `table2` (bla2) VALUES ('Hello World!');
CREATE TABLE `table1` (
`id` INTEGER,
`bla1` TEXT,
PRIMARY KEY(`id`)
);
CREATE TABLE `table2` (
`id` INTEGER,
`bla2` TEXT,
PRIMARY KEY(`id`)
);
INSERT INTO `table2` (bla2) VALUES ('Hello World!');
To copy to clipboard, switch view to plain text mode
Note: If your script is many megabytes, you may want to load it incrementally.
Bookmarks