Linux:C++/Python使用sqlite3

1:安装可视化工具

sudo apt-get install sqlitebrowser

sqlitebrowser 数据库名查看数据库

2:python 接口

import struct
import sqlite3
import base64
import numpy as np


m_dbfile = "/home/lilai/下载/feature1.db"

con=sqlite3.connect(m_dbfile)
cur=con.cursor()
cur.execute("select name from sqlite_master where type='table' order by name")
print (cur.fetchall())

cur.execute("select feature from Md_Feature")

for row in cur:
    print(row)
    print(np.frombuffer(row[0],dtype=np.int8))

cur.close

注意:

feature里面的是人脸特征数据,采用blob类型,即二进制类型。使用np.frombuffer函数可以查看对应的十进制数据。

3:C++接口

C++:源码下载:SQLite Download Page

// ################################# 提取数据库 #################################
    vector<string> u_names;
    int u_count = -1;
    int8_t *pAllFeature = nullptr;

    sqlite3 *m_featureDB{NULL};
    if (SQLITE_OK != sqlite3_open("/data/algo_test/feature.db", &m_featureDB))
    {
        cout << "--- fail1 ------" << endl;
        return -1;
    }

    sqlite3_stmt *stmt;
    const char *sql_cmd1 = "SELECT COUNT(*) FROM Md_Feature";
    const char *sql_cmd2 = "SELECT uid,feature FROM Md_Feature";

    if (sqlite3_prepare(m_featureDB, sql_cmd1, strlen(sql_cmd1), &stmt, NULL) != SQLITE_OK)
    {
        cout << "--- fail1 ------" << endl;
        return -1;
    }
    else
    {
        int ret = sqlite3_step(stmt);
        if (ret == SQLITE_ROW)
        {
            u_count = sqlite3_column_int(stmt, 0);
        }
        else
        {
            cout << "--- fail1 ------" << endl;
            return -1;
        }

        sqlite3_finalize(stmt);
    }

    if (SQLITE_OK != sqlite3_prepare_v2(m_featureDB, sql_cmd2, strlen(sql_cmd2), &stmt, NULL))
    {
        cout << "--- fail2 ------" << endl;
        return -1;
    }
    else
    {
        // u_count = sqlite3_column_count(stmt);
        printf("num_person : %d \n", u_count);

        pAllFeature = (int8_t *)malloc(u_count * 512);
        memset(pAllFeature, 0, u_count * 512);
        int i = 0;

        while (sqlite3_step(stmt) == SQLITE_ROW)
        {
            char *uid = (char *)sqlite3_column_text(stmt, 0);
            if (strlen(uid) > 0)
            {
                u_names.push_back((string)uid);
            }

            void *content = NULL;
            int len = 0;
            content = (void *)sqlite3_column_blob(stmt, 1);
            len = sqlite3_column_bytes(stmt, 1);
            if (len != 0)
            {
                memcpy(pAllFeature + i * 512, content, len);
            }
            i++;
            // for(int i = 0; i<len; i++)
            // {
            //     cout<<i<<" "<<static_cast<int>(u_ft[i])<<endl;
            // }
        }

        sqlite3_finalize(stmt);
    }

    if (SQLITE_OK != sqlite3_close(m_featureDB))
    {
        cout << "--- fail3 ------" << endl;
        return -1;
    }
    // ################################# 提取数据库 #################################

猜你喜欢

转载自blog.csdn.net/lilai619/article/details/130927306