qt實現-給SQLITE添加自定義函數

  須要使用sqlite裏的password對某個字段進行加密,因爲使用的sqlite是由QT封裝好的QSqlDatabase,沒有發現加載擴展函數的方法,因此本身實現了一個。 html

  在網上也沒找到相應的參考,就本身查官方文檔解決了。本篇文章主要是sqlite如何加載外部的函數,並無password函數的實現,我將寫好的函數生成了一個動態庫,由程序動態加載。 ios

 

#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",0,&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 sql

具體接口官方文檔有說明 shell

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 app

相關文章
相關標籤/搜索