初入sqlite3 学习汇总(c接口)

介绍       

 SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比他们都快。SQLite第一个Alpha版本诞生于2000年5月。 至2015年已经有15个年头,SQLite也迎来了一个版本 SQLite 3已经发布。

安装

windows下去sqlite官网下载下载dll-x86(或dll-x64)和 sqlite-tools两个包,然后解压到某个目录下,再将这个安装目录配置环境变量,如何安装没有问题CMD下输入sqlite3将会显示如下版本信息:

linux下通常会自带安装,如果没有执行sudo apt install sqlite3即可。

常用C接口函数

创建或打开数据库文件

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);
int sqlite3_open16(
  const void *filename,   /* Database filename (UTF-16) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);
int sqlite3_open_v2(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb,         /* OUT: SQLite db handle */
  int flags,              /* Flags */
  const char *zVfs        /* Name of VFS module to use */
);

关闭数据

int sqlite3_close(sqlite3*);
int sqlite3_close_v2(sqlite3*);
执行sql语句
int sqlite3_exec(
  sqlite3*,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluated */
  int (*callback)(void*,int,char**,char**),  /* Callback function */
  void *,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
);

exec其实是封装了下面三个函数

语句对象

typedef struct sqlite3_stmt sqlite3_stmt;
int sqlite3_prepare(//准备语句对象
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare_v2(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare_v3(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_step(sqlite3_stmt*);//执行语句
int sqlite3_finalize(sqlite3_stmt *pStmt);//销毁语句

获得绑定的索引个数

int sqlite3_bind_parameter_count(sqlite3_stmt*);通过名称获得项的索引号
int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
通过名称获得项的索引号
int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);

通过索引项获得名称

const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);

为语句对象增加数据

int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
                        void(*)(void*));
int sqlite3_bind_double(sqlite3_stmt*, int, double);
int sqlite3_bind_int(sqlite3_stmt*, int, int);
int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
int sqlite3_bind_null(sqlite3_stmt*, int);
int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
                         void(*)(void*), unsigned char encoding);
int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);

重置语句对象,重新绑定

int sqlite3_reset(sqlite3_stmt *pStmt);

返回查询结果集的某一列

const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
double sqlite3_column_double(sqlite3_stmt*, int iCol);
int sqlite3_column_int(sqlite3_stmt*, int iCol);
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
int sqlite3_column_type(sqlite3_stmt*, int iCol); 

查询获取结果

int sqlite3_get_table(
  sqlite3 *db,          /* An open database */
  const char *zSql,     /* SQL to be evaluated */
  char ***pazResult,    /* Results of the query */
  int *pnRow,           /* Number of result rows written here */
  int *pnColumn,        /* Number of result columns written here */
  char **pzErrmsg       /* Error msg written here */
);
void sqlite3_free_table(char **result); //不要直接用sqlite3_free函数释放

分配和释放内存

void *sqlite3_malloc(int);
void *sqlite3_malloc64(sqlite3_uint64);
void *sqlite3_realloc(void*, int);
void *sqlite3_realloc64(void*, sqlite3_uint64);
void sqlite3_free(void*);
sqlite3_uint64 sqlite3_msize(void*);

执行错误码#define SQLITE_OK           0   /* Successful result */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* An internal logic error in SQLite */
#define SQLITE_PERM         3   /* Access permission denied */
#define SQLITE_ABORT        4   /* Callback routine requested an abort */
#define SQLITE_BUSY         5   /* The database file is locked */
#define SQLITE_LOCKED       6   /* A table in the database is locked */
#define SQLITE_NOMEM        7   /* A malloc() failed */
#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite_interrupt() */
#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define SQLITE_NOTFOUND    12   /* (Internal Only) Table or record not found */
#define SQLITE_FULL        13   /* Insertion failed because database is full */
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
#define SQLITE_EMPTY       16   /* (Internal Only) Database table is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* Too much data for one row of a table */
#define SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */
#define SQLITE_MISMATCH    20   /* Data type mismatch */
#define SQLITE_MISUSE      21   /* Library used incorrectly */
#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define SQLITE_AUTH        23   /* Authorization denied */
#define SQLITE_ROW         100  /* sqlite_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite_step() has finished executing */

案例

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <sqlite3.h>  
  4.   
  5. /*************************** 
  6. typedef int (*sqlite3_callback)( 
  7. void*,    // Data provided in the 4th argument of sqlite3_exec() 
  8. int,        // The number of columns in row  
  9. char**,   // An array of strings representing fields in the row  
  10. char**    // An array of strings representing column names  
  11. ); 
  12.  
  13. ***************************/  
  14.   
  15. /* callback函数只有在对数据库进行select, 操作时才会调用 */  
  16. static int select_callback(void *data, int argc, char **argv, char **azColName){  
  17.    int i;  
  18.    printf("%s", (char*)data);  
  19.    for(i=0; i < argc; i++){  
  20.       printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");  
  21.    }  
  22.    printf("\n");  
  23.    return 0;  
  24. }  
  25.   
  26. int main(int argc, char* argv[])  
  27. {  
  28.    sqlite3 *db;  
  29.    char *zErrMsg = 0;  
  30.    int rc;  
  31.   
  32.    /* 数据库创建或打开 */  
  33.    rc = sqlite3_open("test.db", &db);  
  34.   
  35.    if( rc ){  
  36.       fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));  
  37.       exit(0);  
  38.    }else{  
  39.       fprintf(stderr, "Opened database successfully\n");  
  40.    }  
  41.   
  42.    char* sql;  
  43.    sql = "create table healthinfo (" \  
  44.            "sid int primary key not null," \  
  45.            "name text not null," \  
  46.            "ishealth char(4) not null);";  
  47.   
  48.    /* 创建表 */  
  49.    rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);  
  50.    if( rc != SQLITE_OK ){  
  51.       fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  52.       sqlite3_free(zErrMsg);  
  53.    }else{  
  54.       fprintf(stdout, "Table created successfully\n");  
  55.    }  
  56.   
  57.    sql = "insert into healthinfo (sid, name, ishealth)" \  
  58.            "values (201601001, 'xiaowang', 'yes');" \  
  59.            "insert into healthinfo (sid, name, ishealth)" \  
  60.            "values (201601002, 'xiaoli', 'yes');" \  
  61.            "insert into healthinfo (sid, name, ishealth)" \  
  62.            "values (201601003, 'xiaozhang', 'no');" \  
  63.            "insert into healthinfo (sid, name, ishealth)" \  
  64.            "values (201601004, 'xiaozhou', 'yes');" \  
  65.            "insert into healthinfo (sid, name, ishealth)" \  
  66.            "values (201601005, 'xiaosun', 'yes');";  
  67.   
  68.     /* 插入数据 */  
  69.    rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);  
  70.    if( rc != SQLITE_OK ){  
  71.       fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  72.       sqlite3_free(zErrMsg);  
  73.    }else{  
  74.       fprintf(stdout, "Table insert data successfully\n");  
  75.    }  
  76.   
  77.    char* strname = "xiaoyang";  
  78.    //char strname[256] = {'x','i','a','o','y','a','n','g'};  
  79.    char sql2[256] = {'0'};  
  80.    /* 不推荐使用这种方式 */  
  81.    sprintf(sql2, "insert into healthinfo (sid, name, ishealth) values (201601006, '%s', 'yes');", strname);  
  82.     /* 插入数据 */  
  83.    rc = sqlite3_exec(db, sql2, NULL, NULL, &zErrMsg);  
  84.    if( rc != SQLITE_OK ){  
  85.       fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  86.       sqlite3_free(zErrMsg);  
  87.    }else{  
  88.       fprintf(stdout, "Table insert data successfully\n");  
  89.    }  
  90.   
  91.    /***********  存数据和取数据的第二种方法***********/  
  92.     
  93.    sql = "insert into healthinfo (sid, name, ishealth)" \  
  94.            "values (:sid, :name, :ishealth);";   /* 注: ":sid" 为命名参数 也可以用? 号*/  
  95.   
  96.    sqlite3_stmt *stmt;  
  97.    /* 准备一个语句对象 */  
  98.    sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);   
  99.    /* 语句对象绑定的参数个数也就是上面sql语句values括号中的参数 */  
  100.    printf("max_parameter_count = %d\n", sqlite3_bind_parameter_count(stmt));  
  101.    /* 只有上面指定了:sid这个名字才可以用 */  
  102.    printf("sid parameter index = %d\n", sqlite3_bind_parameter_index(stmt, ":sid"));   
  103.    printf("name parameter index = %d\n", sqlite3_bind_parameter_index(stmt, ":name"));  
  104.    printf("ishealth parameter index = %d\n", sqlite3_bind_parameter_index(stmt, ":ishealth"));  
  105.    /* 如果是?号命名的则返回的文本为null */  
  106.    printf("index = 1 's parameter's name = %s\n", sqlite3_bind_parameter_name(stmt, 1));   
  107.    sqlite3_bind_int(stmt, 1, 201601007);  
  108.    sqlite3_bind_text(stmt, 2, "xiaoqian", -1, NULL); /* 第四个参数设为负数则自动计算第三个参数的长度 */  
  109.    sqlite3_bind_text(stmt, 3, "yes", 3, NULL);  
  110.    //sqlite3_bind_blob(stmt, 1, sectionData, 4096, SQLITE_STATIC); /* 将sectonData 绑定到stmt对象 */  
  111.      
  112.    /* 执行sql 语句对象并判断其返回值 
  113.        发现如果不是select 这样会产生结果集的操作 
  114.        返回值为SQLITE_DONE 或者出错,只有执行sql语句会产生 
  115.        结果集执行step函数才返回SQLITE_ROW*/  
  116.    rc = sqlite3_step(stmt);    
  117.    printf("step() return %s\n", rc == SQLITE_DONE ? "SQLITE_DONE" \  
  118.                                           : rc == SQLITE_ROW ? "SQLITE_ROW" : "SQLITE_ERROR");  
  119.   
  120.     sqlite3_reset(stmt);  /* 如果要重新绑定其他值要reset一下 */  
  121.     sqlite3_bind_int(stmt, 1, 201601008);  
  122.     sqlite3_bind_text(stmt, 2, "xiaowu", -1, NULL); /* 重新绑定值 */  
  123.     sqlite3_bind_text(stmt, 3, "yes", 3, NULL);  
  124.     sqlite3_step(stmt);  /* 再执行 */  
  125.      
  126.    /* 销毁prepare 创建的语句对象 */  
  127.    sqlite3_finalize(stmt);    
  128.   
  129.    /* 取数据 */  
  130.    //sql = "select * from healthinfo;";  
  131.    sql = "select * from healthinfo limit 4 offset 2;";  /* 限制返回4行且从第3行开始 */  
  132.    sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);  
  133.    printf("total_column = %d\n", sqlite3_column_count(stmt));  
  134.      
  135.    /* 遍历执行sql语句后的结果集的每一行数据 */  
  136.    while(sqlite3_step(stmt) == SQLITE_ROW){  
  137.        /* 获得字节数,第二个参数为select结果集合的列号 */  
  138.        /* 由于select 的结果集只有section这一列,因此为0 */  
  139.        int len_sid = sqlite3_column_bytes(stmt, 0);  
  140.        int len_name = sqlite3_column_bytes(stmt, 1);  
  141.        int len_ishealth = sqlite3_column_bytes(stmt, 2);  
  142.          
  143.        printf("sid = %d, len = %d\n", sqlite3_column_int(stmt, 0), len_sid);  
  144.        printf("name = %s, len = %d\n", sqlite3_column_text(stmt, 1), len_name);  
  145.        printf("ishealth = %s, len = %d\n", sqlite3_column_text(stmt, 2), len_ishealth);  
  146.        //unsigned char* srcdata = sqlite3_column_blob(stmt, 0);  /* 取得数据库中的blob数据 */  
  147.    }  
  148.    printf("\n");  
  149.    sqlite3_finalize(stmt);  
  150.    /******************* end ****************************/  
  151.      
  152.   
  153.    const char* data = "select call back function call!\n";  
  154.    /* select 使用*/  
  155.    sql = "select * from healthinfo where ishealth == 'yes';";  
  156.    rc = sqlite3_exec(db, sql, select_callback, data, &zErrMsg);  
  157.    if( rc != SQLITE_OK ){  
  158.       fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  159.       sqlite3_free(zErrMsg);  
  160.    }else{  
  161.       fprintf(stdout, "Table select successfully\n");  
  162.    }  
  163.   
  164.    data = "update call back function call!\n";  
  165.    /* update 使用*/  
  166.    sql = "update healthinfo set ishealth = 'no' where name='xiaoli';" \  
  167.             "select * from healthinfo where ishealth == 'yes';";  
  168.    rc = sqlite3_exec(db, sql, select_callback, data, &zErrMsg);  
  169.    if( rc != SQLITE_OK ){  
  170.       fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  171.       sqlite3_free(zErrMsg);  
  172.    }else{  
  173.       fprintf(stdout, "Table update successfully\n");  
  174.    }  
  175.      
  176.      
  177.    /* 删除表 */  
  178.    sql = "drop table healthinfo;";  
  179.    rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);  
  180.    if( rc != SQLITE_OK ){  
  181.       fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  182.       sqlite3_free(zErrMsg);  
  183.    }else{  
  184.       fprintf(stdout, "Table droped successfully\n");  
  185.    }  
  186.   
  187.   
  188.    char sql5[256];  
  189.    char* tname = "abc";  
  190.    sprintf(sql5, "create table if not exists %s ("\  
  191.                     "id int not null," \  
  192.                     "name text not null);", tname);  
  193.   
  194.    printf("%s\n", sql5);  
  195.   
  196.    /* 创建表 */  
  197.    rc = sqlite3_exec(db, sql5, NULL, NULL, &zErrMsg);  
  198.    if( rc != SQLITE_OK ){  
  199.       fprintf(stderr, "SQL error: %s\n", zErrMsg);  
  200.       sqlite3_free(zErrMsg);  
  201.    }else{  
  202.       fprintf(stdout, "Table created successfully\n");  
  203.    }  
  204.      
  205.    sqlite3_close(db);  
  206. }  

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值