linux c编程操作数据库(sqlite3应用)


C/C++语言中调用 sqlite 的函数接口来实现对数据库的管理(创建数据库、创建表格、插入数据、查询、数据、删除数据等)。

首先要编译好
sqlite的库文件 :
      libsqlite3.a  libsqlite3.la  libsqlite3.so  libsqlite3.so.0  libsqlite3.so.0.8.6  pkgconfig
可执行文件 : 
      sqlite3

本次测试:
      sqlite3的库文件目录是:/usr/local/lib
      可执行文件 sqlite3 的目录是: /usr/local/bin
      头文件 sqlite3.h 的目录是: /usr/local/include

用ls命令查看如下:
[root@localhost config]# ls /usr/local/lib
libclamav.a         libclamunrar_iface.a         libclamunrar.so        libsqlite3.so
libclamav.la        libclamunrar_iface.la        libclamunrar.so.5      libsqlite3.so.0
libclamav.so        libclamunrar_iface.so        libclamunrar.so.5.0.3  libsqlite3.so.0.8.6
libclamav.so.5      libclamunrar_iface.so.5      libmstring.so          pkgconfig
libclamav.so.5.0.3  libclamunrar_iface.so.5.0.3  libsqlite3.a
libclamunrar.a      libclamunrar.la              libsqlite3.la

此目录下包含库文件:
      libsqlite3.a  libsqlite3.la  libsqlite3.so  libsqlite3.so.0  libsqlite3.so.0.8.6  pkgconfig

开始sqlite编程:
      1. 下面是一个C程序的例子,显示怎么使用 sqlite 的 C/C++ 接口. 数据库的名字由第一个参数取得且第个参数或更多的参数是 SQL 执行语句. 
      这个函数调用sqlite3_open() 打开数据库,并且调用sqlite3_close() 关闭数据库连接。
      程序一:opendbslite.c: 

 
 
1.    #include <stdio.h>   
2.    #include <stdlib.h>   
3.    #include <sqlite3.h>   
4.    int main( void )   
5.    {   
6.     sqlite3 *db=NULL;   
7.     char *zErrMsg = 0;   
8.     int rc;   
9.        
10.     //打开指定的数据库文件,如果不存在将创建一个同名的数据库文件   
11.     rc = sqlite3_open("zieckey.db", &db);   
12.     if( rc )   
13.     {   
14.      fprintf(stderr, "Can't open database: %s/n", sqlite3_errmsg(db));   
15.      sqlite3_close(db);   
16.      exit(1);   
17.     }   
18.     else printf("You have opened a sqlite3 database named zieckey.db successfully!/nCongratulations! Have fun !  ^-^ /n");   
19.        
20.     sqlite3_close(db); //关闭数据库   
21.     return 0;   
22.    } 

编译(问题):
[root@localhost liuxltest]# gcc -o opendbsqlite opendbsqlite.c 
/tmp/ccuquUQN.o: In function `main':
opendbsqlite.c:(.text+0x2e): undefined reference to `sqlite3_open'
opendbsqlite.c:(.text+0x42): undefined reference to `sqlite3_errmsg'
opendbsqlite.c:(.text+0x67): undefined reference to `sqlite3_close'
opendbsqlite.c:(.text+0x8a): undefined reference to `sqlite3_close'
collect2: ld returned 1 exit status

编译(解决):
出现上述问题是因为没有找到库文件的问题。
由于用到了用户自己的库文件,所用应该指明所用到的库,我们可以这样编译:
[root@localhost liuxltest]# gcc -o opendbsqlite opendbsqlite.c -lsqlite3
用 -lsqlite3 选项就可以了(前面我们生成的库文件是 libsqlite3.so.0.8.6 等,去掉前面的lib和后面的版本标志,就剩下 sqlite3 了所以是 -lsqlite3 )
执行:
[root@localhost liuxltest]# ./opendbsqlite 
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun !  ^-^ 
[root@localhost liuxltest]#

 

      2. 插入 :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 */
);

程序二:insert.c:

1.    #include <stdio.h>   
2.    #include <stdlib.h>   
3.    #include "sqlite3.h"   
4.    #define _DEBUG_   
5.    int main( void )   
6.    {   
7.    sqlite3 *db=NULL;   
8.    char *zErrMsg = 0;   
9.    int rc;   
10.    rc = sqlite3_open("zieckey.db", &db); //打开指定的数据库文件,如果不存在将创建一个同名的数据库文件   
11.    if( rc )   
12.    {   
13.      fprintf(stderr, "Can't open database: %s/n", sqlite3_errmsg(db));   
14.      sqlite3_close(db);   
15.      exit(1);   
16.    }   
17.    else printf("You have opened a sqlite3 database named zieckey.db successfully!/nCongratulations! Have fun !  ^-^ /n");   
18.    //创建一个表,如果该表存在,则不创建,并给出提示信息,存储在 zErrMsg 中   
19.    char *sql = " CREATE TABLE SensorData(    /   
20.          ID INTEGER PRIMARY KEY,      /   
21.         SensorID INTEGER,         /   
22.          SiteNum INTEGER,        /   
23.          Time VARCHAR(12),           /   
24.          SensorParameter REAL     /   
25.          );" ;   
26.    sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
27.    #ifdef _DEBUG_   
28.            printf("%s/n",zErrMsg);   
29.    #endif   
30.    //插入数据   
31.    char* sql1 = "INSERT INTO /"SensorData/" VALUES( NULL , 1 , 1 , '200605011206', 18.9 );" ;   
32.    sqlite3_exec( db , sql1 , 0 , 0 , &zErrMsg );   
33.    char* sql2 = "INSERT INTO /"SensorData/" VALUES( NULL , 1 , 1 , '200605011306', 16.4 );" ;   
34.    sqlite3_exec( db , sql2 , 0 , 0 , &zErrMsg );   
35.    sqlite3_close(db); //关闭数据库   
36.    return 0;   
37.    } 

编译运行:
[root@localhost liuxltest]# gcc -o insert insert.c -lsqlite3
[root@localhost liuxltest]# ./insert 
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun !  ^-^ 
(null)
(null)
(null)
[root@localhost liuxltest]# 
查看是否插入数据:
[root@localhost liuxltest]# /usr/local/bin/sqlite3 zieckey.db "select * from SensorData"

 

     3. 查询: SELETE
     C语言中查询数据库中的数据。
     函数接口sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );
     解释:
     int sqlite3_get_table(sqlite3*, const char *sql,char***result , int *nrow , int *ncolumn ,char **errmsg );
   result中是以数组的形式存放你所查询的数据,首先是表名,再是数据。
   nrow ,ncolumn分别为查询语句返回的结果集的行数,列数,没有查到结果时返回0
程序三:query.c:

1.    #include <stdio.h>   
2.    #include <stdlib.h>   
3.    #include "sqlite3.h"   
4.    #define _DEBUG_   
5.    int main( void )   
6.    {   
7.     sqlite3 *db=NULL;   
8.     char *zErrMsg = 0;   
9.     int rc;   
10.        
11.     rc = sqlite3_open("zieckey.db", &db); //打开指定的数据库文件,如果不存在将创建一个同名的数据库文件   
12.     if( rc )   
13.     {   
14.      fprintf(stderr, "Can't open database: %s/n", sqlite3_errmsg(db));   
15.      sqlite3_close(db);   
16.      exit(1);   
17.     }   
18.     else printf("You have opened a sqlite3 database named zieckey.db successfully!/nCongratulations! Have fun !  ^-^ /n");   
19.        
20.     //创建一个表,如果该表存在,则不创建,并给出提示信息,存储在 zErrMsg 中   
21.     char *sql = " CREATE TABLE SensorData(  /   
22.          ID INTEGER PRIMARY KEY,  /   
23.         SensorID INTEGER,       /   
24.          SiteNum INTEGER,             /   
25.          Time VARCHAR(12),      /   
26.          SensorParameter REAL          /   
27.          );" ;   
28.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
29.     #ifdef _DEBUG_   
30.            printf("zErrMsg = %s /n", zErrMsg);   
31.     #endif   
32.        
33.     //插入数据    
34.     sql = "INSERT INTO /"SensorData/" VALUES(NULL , 1 , 1 , '200605011206', 18.9 );" ;   
35.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
36.        
37.     sql = "INSERT INTO /"SensorData/" VALUES(NULL , 1 , 1 , '200605011306', 16.4 );" ;   
38.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
39.        
40.        
41.         
42.     int nrow = 0, ncolumn = 0;   
43.     char **azResult; //二维数组存放结果   
44.     //查询数据   
45.     /*  
46.     int sqlite3_get_table(sqlite3*, const char *sql,char***result , int *nrow , int *ncolumn ,char **errmsg );  
47.     result中是以数组的形式存放你所查询的数据,首先是表名,再是数据。  
48.     nrow ,ncolumn分别为查询语句返回的结果集的行数,列数,没有查到结果时返回0  
49.     */   
50.     sql = "SELECT * FROM SensorData ";   
51.     sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );   
52.     int i = 0 ;   
53.     printf( "row:%d column=%d /n" , nrow , ncolumn );   
54.     printf( "/nThe result of querying is : /n" );   
55.        
56.     for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )   
57.      printf( "azResult[%d] = %s/n", i , azResult[i] );   
58.     //释放掉  azResult 的内存空间   
59.     sqlite3_free_table( azResult );   
60.        
61.     #ifdef _DEBUG_   
62.            printf("zErrMsg = %s /n", zErrMsg);   
63.     #endif   
64.     sqlite3_close(db); //关闭数据库   
65.     return 0;   
66.        
67.    }   

这里用到了一个查询的语句是 "SELECT * FROM SensorData " ,
编译运行:
[root@localhost liuxltest]# gcc -o query query.c -lsqlite3 
[root@localhost liuxltest]# ./query 
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) 
[root@localhost liuxltest]# 
      这里我们可以看到,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 为空,表明在执行过程中没有错误信息。

4. 删除:delete
   C语言中删除数据库中的特定的数据。
   程序四: delete.c:

1.    #include <stdio.h>   
2.    #include <stdlib.h>   
3.    #include "sqlite3.h"   
4.    #define _DEBUG_   
5.    int main( void )   
6.    {   
7.     sqlite3 *db=NULL;   
8.     char *zErrMsg = 0;   
9.     int rc;   
10.        
11.     rc = sqlite3_open("zieckey.db", &db); //打开指定的数据库文件,如果不存在将创建一个同名的数据库文件   
12.     if( rc )   
13.     {   
14.      fprintf(stderr, "Can't open database: %s/n", sqlite3_errmsg(db));   
15.      sqlite3_close(db);   
16.      exit(1);   
17.     }   
18.     else printf("You have opened a sqlite3 database named zieckey.db successfully!/nCongratulations! Have fun !  ^-^ /n");   
19.        
20.     //创建一个表,如果该表存在,则不创建,并给出提示信息,存储在 zErrMsg 中   
21.     char *sql = " CREATE TABLE SensorData(   /   
22.          ID INTEGER PRIMARY KEY,         /   
23.         SensorID INTEGER,             /   
24.          SiteNum INTEGER,            /   
25.          Time VARCHAR(12),            /   
26.          SensorParameter REAL         /   
27.          );" ;   
28.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
29.     #ifdef _DEBUG_   
30.            printf("zErrMsg = %s /n", zErrMsg);   
31.        #endif   
32.        
33.     //插入数据    
34.     sql = "INSERT INTO /"SensorData/" VALUES(NULL , 1 , 1 , '200605011206', 18.9 );" ;   
35.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
36.        
37.     sql = "INSERT INTO /"SensorData/" VALUES(NULL , 23 , 45 , '200605011306', 16.4 );" ;   
38.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
39.        
40.     sql = "INSERT INTO /"SensorData/" VALUES(NULL , 34 , 45 , '200605011306', 15.4 );" ;   
41.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
42.        
43.         
44.     int nrow = 0, ncolumn = 0;   
45.     char **azResult; //二维数组存放结果   
46.     //查询数据   
47.     sql = "SELECT * FROM SensorData ";   
48.     sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );   
49.     int i = 0 ;   
50.     printf( "row:%d column=%d /n" , nrow , ncolumn );   
51.     printf( "/nThe result of querying is : /n" );   
52.     for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )   
53.      printf( "azResult[%d] = %s/n", i , azResult[i] );   
54.     //删除数据   
55.     sql = "DELETE FROM SensorData WHERE SensorID = 1 ;" ;   
56.     sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );   
57.     #ifdef _DEBUG_   
58.            printf("zErrMsg = %s /n", zErrMsg);   
59.        #endif   
60.     sql = "SELECT * FROM SensorData ";   
61.     sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );   
62.     printf( "/n/n/n/nrow:%d column=%d " , nrow , ncolumn );   
63.     printf( "/nAfter deleting , the result of querying is : /n" );   
64.     for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )   
65.      printf( "azResult[%d] = %s/n", i , azResult[i] );   
66.       
67.     //释放掉  azResult 的内存空间   
68.     sqlite3_free_table( azResult );   
69.        
70.     #ifdef _DEBUG_   
71.            printf("zErrMsg = %s /n", zErrMsg);   
72.        #endif   
73.     sqlite3_close(db); //关闭数据库   
74.     return 0;   
75.        
76.    } 

编译运行:
[root@localhost liuxltest]# gcc -o delete delete.c -lsqlite3
[root@localhost liuxltest]# ./delete 
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun !  ^-^ 
zErrMsg = (null) 
row:3 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] = 23
azResult[12] = 45
azResult[13] = 200605011306
azResult[14] = 16.4
azResult[15] = 3
azResult[16] = 34
azResult[17] = 45
azResult[18] = 200605011306
azResult[19] = 15.4
zErrMsg = (null) 




row:2 column=5 
After deleting , the result of querying is : 
azResult[0] = ID
azResult[1] = SensorID
azResult[2] = SiteNum
azResult[3] = Time
azResult[4] = SensorParameter
azResult[5] = 2
azResult[6] = 23
azResult[7] = 45
azResult[8] = 200605011306
azResult[9] = 16.4
azResult[10] = 3
azResult[11] = 34
azResult[12] = 45
azResult[13] = 200605011306
azResult[14] = 15.4
zErrMsg = (null) 
[root@localhost liuxltest]# 
      从程序输出结果就可以看出,在删除数据前,我们有三条记录,删除数据后我们发现,数据库内记录少了。从而实现了我们的删除数据目的。

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM