需要使用sqlite里的password对某个字段进行加密,由于使用的sqlite是由QT封装好的QsqlDatabase,没有发现加载扩展函数的方法,所以自己实现了一个。
在网上也没找到相应的参考,就自己查官方文档解决了。本篇文章主要是sqlite如何加载外部的函数,并没有password函数的实现,我将写好的函数生成了一个动态库,由程序动态加载。
#include <iostream> #include <QString> #include <Qtsql/QsqlQuery> #include <Qtsql/QsqlDatabase> #include <Qtsql/QsqlQuery> #include <Qtsql/QsqlError> #include <Qtsql/QsqlDriver> #include <QVariant> #include <sqlite3.h> #include <string.h> using namespace std; void insert_database(QsqlDatabase& database,QString name) { QsqlQuery query(database); if(!query.exec("insert into data(name) values(password('"+name+"') )")) cout<<query.lastError().text().toStdString()<<std::endl; else database.commit(); } int main() { QsqlDatabase database=QsqlDatabase::addDatabase("QsqlITE"); database.setDatabaseName("data.db"); if(!database.open()) { cout<<"open database failure"<<std::endl; return 0; } QVariant handle=database.driver()->handle(); if(!handle.isValid()) { cout<<"handle not valid"<<endl; return 0; } sqlite3* sqlhandle=*static_cast<sqlite3**>(handle.data()); char * error=(char*)sqlite3_malloc(1024); sqlite3_enable_load_extension(sqlhandle,1); if(sqlITE_OK==sqlite3_load_extension(sqlhandle,"/home/quanwei/desktop/my-documents/code/qt/loadsqlitefunction/password.so",&error)); else cout<<"error: "<<error<<std::endl; sqlite3_free(error); insert_database(database,"hello"); database.close(); return 0; }数据库结构也放出来参考
CREATE TABLE data(id integer primary key,name text);
此程序用到的库的支持:
QtCore,Qtsql,sqlite3
具体接口官方文档有说明
Loading An Extension An sqlite extension is a shared library or DLL. To load it,you need to supply sqlite with the name of the file containing the shared library or DLL and an entry point to initialize the extension. In C code,this information is supplied using the sqlite3_load_extension() API. See the documentation on that routine for additional information. Note that different operating systems use different filename suffixes for their shared libraries. Windows use ".dll",Mac uses ".dylib",and most unixes other than mac use ".so". If you want to make your code portable,you can omit the suffix from the shared library filename and the appropriate suffix will be added automatically by the sqlite3_load_extension() interface.不过由于默认load_extension是处于关闭状态,所以需要调用sqlite3_enable_load_extension打开扩展功能
在sqlite3的shell里可以通过执行
sqlite3> .load ./password来加载一个动态库函数,但是由于扩展函数没有储存在数据库中,所以每次打开这个数据库中都要加载一次才能使用自定义函数。
参考:https://www.sqlite.org/loadext.html
原文链接:https://www.f2er.com/sqlite/199991.html