QT中使用QtCipherSqlitePlugin
1.下载QtCipherSqlitePlugin
https://github.com/devbean/QtCipherSqlitePlugin
2.利用QT Creator编译QtCipherSqlitePlugin
应用QT Creator打开QtCipherSqlitePlugin.pro,然后利用QT Creator编译QtCipherSqlitePlugin
3.安装QtCipherSqlitePlugin编译后的dll
将
E:\build-QtCipherSqlitePlugin-Desktop_Qt_6_4_0_MSVC2019_64bit-Debug\sqlitecipher\plugins\sqldrivers
与
E:\build-QtCipherSqlitePlugin-Desktop_Qt_6_4_0_MSVC2019_64bit-Release\sqlitecipher\plugins\sqldrivers
目录下的所有文件放入
C:\Qt\6.4.0\msvc2019_64\plugins\sqldrivers
目录中
4.QT工程中应用
#include <QApplication> #include <QLocale> #include <QTranslator> #include <QStyleFactory> #include <QSurfaceFormat> #include <QTemporaryDir> #include <QtPlugin> #include <QSqlDatabase> #include <QSqlQuery> #include <QSqlError> //打开数据库------------------------------------------------------------------- void openDatabase() { QSqlDatabase database = QSqlDatabase::addDatabase("SQLITECIPHER"); database.setDatabaseName("D:/data/test.db"); database.setPassword("test"); database.setConnectOptions("QSQLITE_CREATE_KEY"); if (!database.open()) { qDebug() << "Can not open connection: " << database.lastError().driverText(); exit(-1); } qDebug() << "open connection successful \n"; database.close(); } //创建数据库------------------------------------------------------------------- void createDatabase() { QTemporaryDir tmpDir; QString dbname = QDir(tmpDir.path()).absoluteFilePath("test_plugin.db"); // QString dir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); // QString dbname = dir + "/local.db"; // qDebug() << dbname; QSqlDatabase database = QSqlDatabase::addDatabase("SQLITECIPHER", "db"); database.setDatabaseName("D:/data/test-01.db"); database.setPassword("test"); database.setConnectOptions("QSQLITE_CREATE_KEY"); if (!database.open()) { qDebug() << "Can not open connection: " << database.lastError().driverText(); exit(-1); } // QSqlQuery q(database); QStringList queries; queries << "create table IF NOT EXISTS foo(bar integer)" << "insert into foo values (42)"; for (const QString &qs : qAsConst(queries)) { if (!q.exec(qs)) { qDebug() << "Can not open connection: " << q.lastError().text(); } } database.close(); } //读写数据库------------------------------------------------------------------- void readWithPassphrase() { QSqlDatabase database = QSqlDatabase::addDatabase("SQLITECIPHER", "db"); database.setDatabaseName("D:/data/test-01.db"); database.setPassword("test"); if (!database.open()) { qDebug() << "Can not open connection: " << database.lastError().driverText(); exit(-1); } QSqlQuery q(database); if (!q.exec("select bar from foo")) { qDebug() << "Can not open connection: " << q.lastError().text(); } // if (q.next()) { qDebug() << q.value(0).toInt() << "\n"; } // database.close(); } //---------------------------------------------------------------- int main(int argc, char *argv[]) { qDebug() << QSqlDatabase::drivers(); // openDatabase(); // // createDatabase(); // readWithPassphrase(); }
--------------------------