我通过sqlitestudio SQLSicpher制作了一个密码sqlite数据库文件,如何从qt访问数据库?
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbLocation);
db.setPassword("thPassworde");
但无法打开数据库。
答案 0 :(得分:1)
Qt并不正式支持SQLCipher,但是有几个项目在它们之间QtCipherSqlitePlugin创建了一个驱动程序,要安装该驱动程序,我使用以下命令:
git clone git@github.com:devbean/QtCipherSqlitePlugin.git
qmake
make
sudo make install
注意:如果您使用的是Windows,则必须使用jom
,nmake
或mingw32-make
,具体取决于您的配置。
该库提供了一个example project,其中main.cpp如下:
#include <QtSql>
#include <QCoreApplication>
#ifdef Q_OS_IOS
# include <QtPlugin>
Q_IMPORT_PLUGIN(SqliteCipherDriverPlugin)
#endif
#define CONNECTION_FAILED -1
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Q_UNUSED(app);
qDebug() << QSqlDatabase::drivers();
QString dir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
// QString DB_FILE_PATH = dir + "/test_chacha20.db";
QString DB_FILE_PATH = dir + "/test_sqlcipher.db";
qDebug() << "DB File Path is:" << DB_FILE_PATH;
QSqlDatabase dbconn = QSqlDatabase::addDatabase("SQLITECIPHER");
dbconn.setDatabaseName(DB_FILE_PATH);
dbconn.setPassword("test");
dbconn.setConnectOptions("QSQLITE_USE_CIPHER=sqlcipher; QSQLITE_ENABLE_REGEXP");
if (!dbconn.open()) {
qDebug() << "Can not open connection: " << dbconn.lastError().driverText();
exit(CONNECTION_FAILED);
}
QSqlQuery query;
query.exec("create table mapping (id int, name varchar)");
query.exec("insert into mapping values (1, 'AAA')");
query.exec("insert into mapping values (2, 'BBB')");
query.exec("insert into mapping values (3, 'CCC')");
query.exec("insert into mapping values (4, 'DDD')");
query.exec("insert into mapping values (5, 'EEE')");
query.exec("insert into mapping values (6, 'FFF')");
query.exec("insert into mapping values (7, 'GGG')");
query.exec("select * from mapping where name regexp '(a|A)$'");
if (query.next()) {
qDebug() << "Regexp result: " << query.value(0).toInt() << ": " << query.value(1).toString();
} else {
qDebug() << "This plugin does not support regexp.";
}
qDebug() << "----------" << endl;
query.exec("select id, name from mapping");
while (query.next()) {
qDebug() << query.value(0).toInt() << ": " << query.value(1).toString();
}
qDebug() << "----------" << endl;
query.exec("update mapping set name='ZZZ' where id=1");
query.exec("select id, name from mapping");
while (query.next()) {
qDebug() << query.value(0).toInt() << ": " << query.value(1).toString();
}
qDebug() << "----------" << endl;
query.exec("delete from mapping where id=4");
query.exec("select id, name from mapping");
while (query.next()) {
qDebug() << query.value(0).toInt() << ": " << query.value(1).toString();
}
query.exec("drop table mapping");
dbconn.close();
return 0;
}