from : http://blog.chinaunix.net/uid-21556133-id-118208.html
安裝Sqlite3:
從www.sqlite.org上下載Sqlite3.2.2運原始碼,依照Readme中的步驟:
tar xzf sqlite3.2.2.tar.gz
mkdir bld
cd bld
../sqlite3.2.2/configure
make
make install
然後在shell下運行 sqlite3 test.db命令可以檢驗是否已經安裝成功。
0. 引言
我們這篇文章主要講述了如何在C/C++語言中調用 sqlite 的函數介面來實現對資料庫的管理,
包括建立資料庫、建立表格、插入資料、查詢資料、刪除資料等。
1. 說明
這裡我們假設你已經編譯好了sqlite的庫檔案 :
libsqlite3.a libsqlite3.la libsqlite3.so libsqlite3.so.0 libsqlite3.so.0.8.6 pkgconfig
和可執行檔 : sqlite3
我們再假設你的sqlite3的安裝目錄在 /usr/local/sqlite3 目錄下。
如果不是,我們可以這樣做,將你的安裝檔案複製到 /usr/local/sqlite3 這個目錄,
這樣我們好在下面的操作中更加統一,從而減少出錯的機率
例如:[root@localhost home]# cp -rf sqlite-3.3.8-ix86/ /usr/local/sqlite3
這裡假設 /home/sqlite-3.3.8-ix86/ 是你的安裝目錄,也就是說你的sqlite原來就是安裝在這裡
這樣之後,我們的sqlite3的庫檔案目錄是:/usr/local/sqlite3/lib
可執行檔 sqlite3 的目錄是: /usr/local/sqlite3/bin
標頭檔 sqlite3.h 的目錄是: /usr/local/sqlite3/include
好拉,現在開始我們的Linux下sqlite3編程之旅。
2. 開始
這裡我們現在進行一個測試。
現在我們來寫個C/C++程式,調用 sqlite 的 API 介面函數。
下面是一個C程式的例子,顯示怎麼使用 sqlite 的 C/C++ 介面. 資料庫的名字由第一個參數取得且第二個參數或更多的參數是 SQL 執行語句. 這個函數調用sqlite3_open() 在 16 行開啟資料庫,並且sqlite3_close() 在 25 行關閉資料庫連接。
[root@localhost temp]# vi opendbsqlite.c
按下 i 鍵切換到輸入模式,輸入下列代碼:
// name: opendbsqlite.c
// This prog is used to test C/C++ API for sqlite3.It is very simple,ha!
// Author : zieckey All rights reserved.
// data : 2006/11/13
#include <stdio.h>
#include <sqlite3.h>
int main( void )
{
sqlite3 *db=NULL;
char *zErrMsg = 0;
int rc;
//開啟指定的資料庫檔案,如果不存在將建立一個同名的資料庫檔案
rc = sqlite3_open("zieckey.db", &db);
if( rc )
{
fprintf(stderr, "Can't open database: %s
", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
else printf("You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
");
sqlite3_close(db); //關閉資料庫
return 0;
}
退出,儲存。(代碼輸入完成後,按下 Esc 鍵,然後輸入: :wq ,斷行符號就好拉)
好拉,現在編譯:[root@localhost temp]# gcc opendbsqlite.c -o db.out
或者遇到這樣的問題:
[root@localhost temp]# gcc opendbsqlite.c -o db.out
opendbsqlite.c:11:21: sqlite3.h: 沒有那個檔案或目錄
opendbsqlite.c: In function `main':
opendbsqlite.c:19: `sqlite3' undeclared (first use in this function)
opendbsqlite.c:19: (Each undeclared identifier is reported only once
opendbsqlite.c:19: for each function it appears in.)
opendbsqlite.c:19: `db' undeclared (first use in this function)
這是由於沒有找到標頭檔的原因。
也許會碰到類似這樣的問題:
[root@localhost temp]# gcc opendbsqlite.c -o db.out
/tmp/ccTkItnN.o(.text+0x2b): In function `main':
: undefined reference to `sqlite3_open'
/tmp/ccTkItnN.o(.text+0x45): In function `main':
: undefined reference to `sqlite3_errmsg'
/tmp/ccTkItnN.o(.text+0x67): In function `main':
: undefined reference to `sqlite3_close'
/tmp/ccTkItnN.o(.text+0x8f): In function `main':
: undefined reference to `sqlite3_close'
collect2: ld returned 1 exit status
這是個沒有找到庫檔案的問題。
下面我們著手解決這些問題。
由於用到了使用者自己的庫檔案,所用應該指明所用到的庫,我們可以這樣編譯:
[root@localhost temp]# gcc opendbsqlite.c -o db.out -lsqlite3
我用用 -lsqlite3 選項就可以了(前面我們產生的庫檔案是 libsqlite3.so.0.8.6 等,
去掉前面的lib和後面的版本標誌,就剩下 sqlite3 了所以是 -lsqlite3 )。
如果我們在編譯安裝的時候,選擇了安裝路徑,例如這樣的話:
.......
# ../sqlite/configure --prefix=/usr/local/sqlite3
# make
.......
這樣編譯安裝時,sqlite的庫檔案將會產生在 /usr/local/sqlite3/lib 目錄下
sqlite的標頭檔將會產生在 /usr/local/sqlite3/include 目錄下
這時編譯還要指定庫檔案路徑,因為系統預設的路徑沒有包含 /usr/local/sqlite3/lib
[root@localhost temp]# gcc opendbsqlite.c -o db.out -lsqlite3 -L/usr/local/sqlite3/lib
如果還不行的話,可能還需要指定標頭檔 sqlite3.h 的路徑,如下:
[root@localhost temp]# gcc opendbsqlite.c -o db.out -lsqlite3 -L/usr/local/sqlite3/lib -I/usr/local/sqlite3/include
這樣編譯應該就可以了 ,運行:
[root@localhost temp]# ./db.out
./db.out: error while loading shared libraries: libsqlite3.so.0: cannot open shared object file: No such file or directory
運行是也許會出現類似上面的錯誤。
這個問題因為剛剛編譯的時候沒有選擇靜態編譯,那麼按照預設的編譯就動態編譯的。
動態編譯後,由於可執行檔在運行時要調用系統庫檔案,
那麼沿著系統預設的庫檔案搜尋路徑搜尋,就可能找不到我們現在所需的庫檔案。
致使出現 "error while loading shared libraries" 等錯誤。
我們可以這樣解決:
方法一:靜態編譯
在編譯時間加上 -static 參數,例如
[root@localhost temp]# gcc opendbsqlite.c -o db.out -lsqlite3 -L/usr/local/sqlite3/lib -I/usr/local/sqlite3/include -static
[root@localhost temp]# ll
總用量 1584
-rwxr-xr-x 1 root root 1596988 11月 13 10:50 db.out
-rw-r--r-- 1 root root 614 11月 13 10:31 opendbsqlite.c
可以看到輸出檔案 db.out ,其大小為: 1596988k
運行,好了,沒有出現錯誤
[root@localhost temp]# ./db.out
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
方法二:重新設定系統內容變數 LD_LIBRARY_PATH
這時需要指定 libsqlite3.so.0 庫檔案的路徑,也就是配置系統內容變數 LD_LIBRARY_PATH ,
使系統能夠找到 libsqlite3.so.0 。
去掉 -static ,在編譯:
[root@localhost temp]# gcc opendbsqlite.c -o db.out -lsqlite3 -L/usr/local/sqlite3/lib -I/usr/local/sqlite3/include
[root@localhost temp]# ll
總用量 36
-rwxr-xr-x 1 root root 12716 11月 13 10:56 db.out
-rw-r--r-- 1 root root 614 11月 13 10:31 opendbsqlite.c
[root@localhost temp]#
可以看到輸出檔案 db.out ,其大小為: 12716k,比剛才的靜態編譯要小得多。
所以我們推薦使用動態編譯的方法。
好了,現在我們來指定系統內容變數 LD_LIBRARY_PATH 的值
在shell下輸入:
[root@localhost temp]# export LD_LIBRARY_PATH=/usr/local/sqlite3/lib:$LD_LIBRARY_PATH
再運行
[root@localhost temp]# ./db.out
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
是不是很有成就感阿 ,呵呵,這個上手還是很快的。
3. 插入:insert
剛剛我們知道了怎麼調用 sqlite3 的C/C++的API函數介面,下面我們看看怎麼在C語言中向資料庫插入資料。
好的,我們現編輯一段c代碼,取名為 insert.c
// name: insert.c
// This prog is used to test C/C++ API for sqlite3 .It is very simple,ha !
// Author : zieckey All rights reserved.
// data : 2006/11/18
#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#define _DEBUG_
int main( void )
{
sqlite3 *db=NULL;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("zieckey.db", &db); //開啟指定的資料庫檔案,如果不存在將建立一個同名的資料庫檔案
if( rc )
{
fprintf(stderr, "Can't open database: %s
", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
else printf("You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
");
//建立一個表,如果該表存在,則不建立,並給出提示資訊,儲存在 zErrMsg 中
char *sql = " CREATE TABLE SensorData(
ID INTEGER PRIMARY KEY,
SensorID INTEGER,
SiteNum INTEGER,
Time VARCHAR(12),
SensorParameter REAL
);" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
#ifdef _DEBUG_
printf("%s
",zErrMsg);
#endif
//插入資料
sql = "INSERT INTO "SensorData" VALUES( NULL , 1 , 1 , '200605011206', 18.9 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
sql = "INSERT INTO "SensorData" VALUES( NULL , 1 , 1 , '200605011306', 16.4 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
sqlite3_close(db); //關閉資料庫
return 0;
}
好的,將上述代碼寫入一個檔案,並將其命名為 insert.c 。
解釋:
sqlite3_exec的函數原型說明如下:
int sqlite3_exec(
sqlite3*, /* An open database */
const char *sql, /* SQL to be executed */
sqlite_callback, /* Callback function */
void *, /* 1st argument to callback function */
char **errmsg /* Error msg written here */
);
編譯:
[root@localhost temp]# gcc insert.c -lsqlite3 -L/usr/local/sqlite3/lib -I/usr/local/sqlite3/include
insert.c:28:21: warning: multi-line string literals are deprecated
[root@localhost temp]#
執行
[root@localhost temp]# ./a.out
./a.out: error while loading shared libraries: libsqlite3.so.0: cannot open shared object file: No such file or directory
[root@localhost temp]#
同樣的情況,如上文處理方法:
[root@localhost temp]# export LD_LIBRARY_PATH=/usr/local/sqlite3/lib:$LD_LIBRARY_PATH
[root@localhost temp]# ./a.out
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
(null)
(null)
(null)
[root@localhost temp]#
運行成功了,好了,現在我們來看看是否插入了資料
[root@localhost temp]# /usr/local/sqlite3/bin/sqlite3 zieckey.db
SQLite version 3.3.8
Enter ".help" for instructions
sqlite> select * from SensorData;
1|1|1|200605011206|18.9
2|1|1|200605011306|16.4
sqlite>
哈哈,已經插入進去了,不是嗎?
很簡單是不?
4. 查詢: SELETE
好了,我們知道了怎麼調用 sqlite3 的C/C++的API函數介面去建立資料庫、建立表格、並插入資料,
下面我們看看怎麼在C語言中查詢資料庫中的資料。
好的,我們現編輯一段c代碼,取名為 query.c
// name: query.c
// This prog is used to test C/C++ API for sqlite3 .It is very simple,ha !
// Author : zieckey All rights reserved.
// data : 2006/11/18
#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#define _DEBUG_
int main( void )
{
sqlite3 *db=NULL;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("zieckey.db", &db); //開啟指定的資料庫檔案,如果不存在將建立一個同名的資料庫檔案
if( rc )
{
fprintf(stderr, "Can't open database: %s
", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
else printf("You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
");
//建立一個表,如果該表存在,則不建立,並給出提示資訊,儲存在 zErrMsg 中
char *sql = " CREATE TABLE SensorData(
ID INTEGER PRIMARY KEY,
SensorID INTEGER,
SiteNum INTEGER,
Time VARCHAR(12),
SensorParameter REAL
);" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
#ifdef _DEBUG_
printf("zErrMsg = %s
", zErrMsg);
#endif
//插入資料
sql = "INSERT INTO "SensorData" VALUES(NULL , 1 , 1 , '200605011206', 18.9 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
sql = "INSERT INTO "SensorData" VALUES(NULL , 1 , 1 , '200605011306', 16.4 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
int nrow = 0, ncolumn = 0;
char **azResult; //二維數組存放結果
//查詢資料
/*
int sqlite3_get_table(sqlite3*, const char *sql,char***result , int *nrow , int *ncolumn ,char **errmsg );
result中是以數組的形式存放你所查詢的資料,首先是表名,再是資料。
nrow ,ncolumn分別為查詢語句返回的結果集的行數,列數,沒有查到結果時返回0
*/
sql = "SELECT * FROM SensorData ";
sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );
int i = 0 ;
printf( "row:%d column=%d
" , nrow , ncolumn );
printf( "
The result of querying is :
" );
for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )
printf( "azResult[%d] = %s
", i , azResult[i] );
//釋放掉 azResult 的記憶體空間
sqlite3_free_table( azResult );
#ifdef _DEBUG_
printf("zErrMsg = %s
", zErrMsg);
#endif
sqlite3_close(db); //關閉資料庫
return 0;
}
我們這裡用到了一個查詢的語句是 "SELECT * FROM SensorData " ,
在C語言中對應的函數介面是 sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );
這個函數介面的解釋在程式中已經注釋。
下面我們編譯運行下看看,
[root@localhost temp]# export LD_LIBRARY_PATH=/usr/local/sqlite3/lib:$LD_LIBRARY_PATH
[root@localhost temp]# gcc query.c -lsqlite3 -L/usr/local/sqlite3/lib -I/usr/local/sqlite3/include
query.c:29:21: warning: multi-line string literals are deprecated
[root@localhost temp]# ./a.out
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
zErrMsg = (null)
row:2 column=5
The result of querying is :
azResult[0] = ID
azResult[1] = SensorID
azResult[2] = SiteNum
azResult[3] = Time
azResult[4] = SensorParameter
azResult[5] = 1
azResult[6] = 1
azResult[7] = 1
azResult[8] = 200605011206
azResult[9] = 18.9
azResult[10] = 2
azResult[11] = 1
azResult[12] = 1
azResult[13] = 200605011306
azResult[14] = 16.4
zErrMsg = (null)
這裡我們可以看到,azResult 的前面 5 個資料正好是我們的表 SensorData 的列屬性,
之後才是我們要查詢的資料。所以我們的程式中才有 i<( nrow + 1 ) * ncolumn 的判斷條件:
for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )
printf( "azResult[%d] = %s ", i , azResult[i] );
輸出中有 zErrMsg = (null) 這樣的字句,這是 zErrMsg 保留的錯誤資訊,
正如你所看到的,zErrMsg 為空白,表明在執行過程中沒有錯誤資訊。