C 操作SQLite資料庫

2021-06-07 04:13:30 字數 2133 閱讀 3291

在使用c++操作sqlite之前,需要獲得sqlite3.h,sqlite3.lib,sqlite3.dll,大家可以在

這裡

int sqlite3_open(char *path,sqlite3 **db)

這個函式開啟資料庫,第乙個引數為sqlite檔案的位址,第二個引數是sqlite3的指標的指標,也就是二級指標。

返回值為sqlite_ok則成功開啟資料庫。

sqlite3_close(sqlite3 *db)

這個函式關閉資料庫,引數是sqlite3的指標。

sqlite3_exec(sqlite3 *db,char *sql,int l,int m,int n)

這個函式執行sql語句,如果我們不需要返回的結果就用這個函式執行sql語句。第乙個引數是sqlite3的指標,第二個引數為執行的sql語句,後面3個引數我們不用關心,都設為0。

sqlite3_get_table(sqlite *db,char *sql,char ***result,int *row,int *column,int k);

這個函式執行查詢語句,返回我們所需要的資訊。第乙個引數是sqlite的指標,第二個引數是sql語句,第三個引數是返回的資訊。row是返回的行數,column是返回的列數,最後乙個引數設為0就行了。

因為我們使用的是gb2312,而sqlite使用的是utf-8,所以在使用中會出現中文亂碼,為了解決這個問題,我介紹兩個有用的函式

utf-8轉換到gb3212

char* u2g(const char* utf8)

gb2312到utf-8的轉換

char* g2u(const char* gb2312)

這兩個函式會用就行,需要引入windows.h標頭檔案

在我的工程中,我將api封裝了一下,便於操作。

我新建了乙個叫做sqlitehelper類  標頭檔案如下

#if !defined(afx_sqlitehelper_h__59f8c44e_0d98_4422_aeb1_2fd927ee8902__included_)

#define afx_sqlitehelper_h__59f8c44e_0d98_4422_aeb1_2fd927ee8902__included_

#if _msc_ver > 1000

#pragma once

#endif // _msc_ver > 1000

#include "sqlite3.h"

#include class sqlitehelper

;#endif // !defined(afx_sqlitehelper_h__59f8c44e_0d98_4422_aeb1_2fd927ee8902__included_)

原始檔如下

#include "sqlitehelper.h"

#include //

// construction/destruction

//sqlitehelper::sqlitehelper()

sqlitehelper::~sqlitehelper()

void sqlitehelper::execsql(char *sql)

char **sqlitehelper::rawquery(char *sql,int *row,int *column,char **result)

void sqlitehelper::opendb(char *path)

//gb2312到utf-8的轉換

char* g2u(const char* gb2312)

void main()

這裡我講解一下re[(2+1)*col+1]

re是指向陣列的指標。(2+1)為第3行,1表示第2列。

從中可以看出,我將「張譯成」這個字串讀出了。大家注意,在寫入的時候,如果要寫入中文的話,就要將中文從gb2312轉換到utf-8再寫入,大家根據自己專案的需要,函式我已經給出了。

c 操作Sqlite資料庫

宣告變數 system.data.sqlite.sqlitecommand cmd new system.data.sqlite.sqlitecommand system.data.sqlite.sqliteconnection conn null string sql string value i...

C 操作SQLite資料庫

在使用c 操作sqlite之前,需要獲得sqlite3.h,sqlite3.lib,sqlite3.dll,大家可以在 這裡 int sqlite3 open char path,sqlite3 db 這個函式開啟資料庫,第乙個引數為sqlite檔案的位址,第二個引數是sqlite3的指標的指標,也...

C 操作SQLite資料庫

在使用c 操作sqlite之前,需要獲得sqlite3.h,sqlite3.lib,sqlite3.dll,大家可以在 這裡 int sqlite3 open char path,sqlite3 db 這個函式開啟資料庫,第乙個引數為sqlite檔案的位址,第二個引數是sqlite3的指標的指標,也...