Linux下用到數據庫sqlite3

最近在Linux下用到數據庫sqlite3,因而開始了該方面的學習。 

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\n", sqlite3_errmsg(db)); 

sqlite3_close(db); 

exit(1); 



else printf("You have opened a sqlite3 database named zieckey.db successfully!\nCongratulations! Have fun ! ^-^ \n"); 


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\n", sqlite3_errmsg(db)); 
sqlite3_close(db); 
exit(1); 

else printf("You have opened a sqlite3 database named zieckey.db successfully!\nCongratulations! Have fun ! ^-^ \n"); 


//建立一個表,若是該表存在,則不建立,並給出提示信息,存儲在 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\n",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\n", sqlite3_errmsg(db)); 
sqlite3_close(db); 
exit(1); 

else printf("You have opened a sqlite3 database named zieckey.db successfully!\nCongratulations! Have fun ! ^-^ \n"); 


//建立一個表,若是該表存在,則不建立,並給出提示信息,存儲在 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 \n", 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 \n" , nrow , ncolumn ); 
printf( "\nThe result of querying is : \n" ); 

for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ ) 
printf( "azResult[%d] = %s\n", i , azResult[i] ); 

//釋放掉 azResult 的內存空間 
sqlite3_free_table( azResult ); 

#ifdef _DEBUG_ 
printf("zErrMsg = %s \n", 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\n", i , azResult[i] ); 






輸出中有 zErrMsg = (null) 這樣的字句,這是 zErrMsg 保留的錯誤信息, 
正如你所看到的,zErrMsg 爲空,代表在執行過程當中沒有錯誤信息。 





SQLite3.3.6在ARM2410上的移植 

要將SQLite3.3.6移植到ARM2410開發板上,除了要有底層操做系統的支持外,還必需要有相應的交叉編譯工具鏈。因爲ARM2410開發板採用的是ARM-Linux做爲底層操做系統,所以須要首先安裝ARM-Linux工具鏈。 
1.交叉編譯環境創建: 
拷貝cross-2.95.3.tar.bz2到/usr/local目錄下並解壓縮。 
cp cross-2.95.3.tar.bz2 /usr/local/arm 
tar –jxvf cross-2.95.3.tar.bz2 

2.編譯SQLite-3.3.6 
(1)在/root下創建目錄sqlite,拷貝sqlite-3.3.6.tar.gz到該目錄同時解壓縮。 
tar –zxvf sqlite-3.3.6.tar.gz 
(2)新建目錄: 
cd /sqlite-3.3.6 
mkdir build 
(3)修改配置文件 
vi configure 
修改如下幾個部分: 
# if 
test "$cross_compiling" = "yes"; then 
# { { echo "$as_me:$LINENO: error: unable to find a compiler for building build tools" >&5 
#echo "$as_me: error: unable to find a compiler for building build tools" >&2;} 
# { (exit 1); exit 1; }; } 
# fi 

#else 
# test "$cross_compiling" = yes && 
# { { echo "$as_me:$LINENO: error: cannot check for file existence when cross compiling" >&5 
#echo "$as_me: error: cannot check for file existence when cross compiling" >&2;} 
# { (exit 1); exit 1; }; } 

#else 
# test "$cross_compiling" = yes && 
# { { echo "$as_me:$LINENO: error: cannot check for file existence when cross compiling" >&5 
#echo "$as_me: error: cannot check for file existence when cross compiling" >&2;} 
# { (exit 1); exit 1; }; } 

進入目錄build: 
cd build 
../ configure --disable-tcl --host=arm-linux 
這樣在build目錄中就將生成Makefile和一個libtool腳本 
(4)修改Makefile文件: 
cd build 
vi Makefile 
將下面的這行 
BCC = arm-linux-gcc -g -O2 
改爲: 
BCC = gcc -g -O2 
將下面的這行: 
sqlite3$(TEXE): $(TOP)/src/shell.c .libs/libsqlite3.la sqlite3.h 
改爲: 
sqlite3$(TEXE): $(TOP)/src/shell.c .libs/libsqlite3.a sqlite3.h 
咱們都是將sqlite放到arm-linux的硬件板子上運行,因此咱們通常將其編譯成靜態連接的形式。 
保存Makefile文件後退出。 
(5)編譯: 
執行make命令便可完成編譯。 
編譯完成後,在build目錄下生成許多.o和.lo文件。但最重要的時文件sqlite3。 
file sqlite3 
sqlite3: ELF 32-bit LSB executable, ARM, version 1 (ARM), for GNU/Linux 2.0.0, dynamically linked (uses shared libs), not stripped 
由此可知,此時生成的sqlite文件是還未strip過的。執行命令arm-linux-strip, 去掉其中的調試信息,這樣文件將減小不少。 
arm-linux-strip sqlite3 

再次用file命令查看sqlite3的信息: 
file sqlite3 
sqlite3: ELF 32-bit LSB executable, ARM, version 1 (ARM), for GNU/Linux 2.0.0, dynamically linked (uses shared libs), stripped 
這就是在開發板上能夠直接運行的可執行文件。 
經過nfs將這些文件下載到開發板上。 
須要注意: 
拷貝是須要加上 –arf選項,由於libsqlite3.so,libsqlite3.so.0是連接到libsqlite3.so.0.8.6的。 
cp –arf libsqlite3.so libsqlite3.so.0. libsqlite3.so.0.8.6 /usr/lib 
cp sqlite3 /mnt/nfs 
(6)測試結果: 
chmod 777 sqlite3 
編輯測試程序:test.c 
編譯:arm-linux-gcc test.c -L.libs -lsqlite3 –static 
arm-linux-strip a.out 
將其下載到開發板上: 
執行:a.out ex "select * from tbl"  
mysql

相關文章
相關標籤/搜索