sqlite3
介绍
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 */
案例
- #include <stdio.h>
- #include <string.h>
- #include <sqlite3.h>
- /***************************
- typedef int (*sqlite3_callback)(
- void*, // Data provided in the 4th argument of sqlite3_exec()
- int, // The number of columns in row
- char**, // An array of strings representing fields in the row
- char** // An array of strings representing column names
- );
- ***************************/
- /* callback函数只有在对数据库进行select, 操作时才会调用 */
- static int select_callback(void *data, int argc, char **argv, char **azColName){
- int i;
- printf("%s", (char*)data);
- for(i=0; i < argc; i++){
- printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
- }
- printf("\n");
- return 0;
- }
- int main(int argc, char* argv[])
- {
- sqlite3 *db;
- char *zErrMsg = 0;
- int rc;
- /* 数据库创建或打开 */
- rc = sqlite3_open("test.db", &db);
- if( rc ){
- fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
- exit(0);
- }else{
- fprintf(stderr, "Opened database successfully\n");
- }
- char* sql;
- sql = "create table healthinfo (" \
- "sid int primary key not null," \
- "name text not null," \
- "ishealth char(4) not null);";
- /* 创建表 */
- rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);
- if( rc != SQLITE_OK ){
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_free(zErrMsg);
- }else{
- fprintf(stdout, "Table created successfully\n");
- }
- sql = "insert into healthinfo (sid, name, ishealth)" \
- "values (201601001, 'xiaowang', 'yes');" \
- "insert into healthinfo (sid, name, ishealth)" \
- "values (201601002, 'xiaoli', 'yes');" \
- "insert into healthinfo (sid, name, ishealth)" \
- "values (201601003, 'xiaozhang', 'no');" \
- "insert into healthinfo (sid, name, ishealth)" \
- "values (201601004, 'xiaozhou', 'yes');" \
- "insert into healthinfo (sid, name, ishealth)" \
- "values (201601005, 'xiaosun', 'yes');";
- /* 插入数据 */
- rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);
- if( rc != SQLITE_OK ){
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_free(zErrMsg);
- }else{
- fprintf(stdout, "Table insert data successfully\n");
- }
- char* strname = "xiaoyang";
- //char strname[256] = {'x','i','a','o','y','a','n','g'};
- char sql2[256] = {'0'};
- /* 不推荐使用这种方式 */
- sprintf(sql2, "insert into healthinfo (sid, name, ishealth) values (201601006, '%s', 'yes');", strname);
- /* 插入数据 */
- rc = sqlite3_exec(db, sql2, NULL, NULL, &zErrMsg);
- if( rc != SQLITE_OK ){
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_free(zErrMsg);
- }else{
- fprintf(stdout, "Table insert data successfully\n");
- }
- /*********** 存数据和取数据的第二种方法***********/
- sql = "insert into healthinfo (sid, name, ishealth)" \
- "values (:sid, :name, :ishealth);"; /* 注: ":sid" 为命名参数 也可以用? 号*/
- sqlite3_stmt *stmt;
- /* 准备一个语句对象 */
- sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);
- /* 语句对象绑定的参数个数也就是上面sql语句values括号中的参数 */
- printf("max_parameter_count = %d\n", sqlite3_bind_parameter_count(stmt));
- /* 只有上面指定了:sid这个名字才可以用 */
- printf("sid parameter index = %d\n", sqlite3_bind_parameter_index(stmt, ":sid"));
- printf("name parameter index = %d\n", sqlite3_bind_parameter_index(stmt, ":name"));
- printf("ishealth parameter index = %d\n", sqlite3_bind_parameter_index(stmt, ":ishealth"));
- /* 如果是?号命名的则返回的文本为null */
- printf("index = 1 's parameter's name = %s\n", sqlite3_bind_parameter_name(stmt, 1));
- sqlite3_bind_int(stmt, 1, 201601007);
- sqlite3_bind_text(stmt, 2, "xiaoqian", -1, NULL); /* 第四个参数设为负数则自动计算第三个参数的长度 */
- sqlite3_bind_text(stmt, 3, "yes", 3, NULL);
- //sqlite3_bind_blob(stmt, 1, sectionData, 4096, SQLITE_STATIC); /* 将sectonData 绑定到stmt对象 */
- /* 执行sql 语句对象并判断其返回值
- 发现如果不是select 这样会产生结果集的操作
- 返回值为SQLITE_DONE 或者出错,只有执行sql语句会产生
- 结果集执行step函数才返回SQLITE_ROW*/
- rc = sqlite3_step(stmt);
- printf("step() return %s\n", rc == SQLITE_DONE ? "SQLITE_DONE" \
- : rc == SQLITE_ROW ? "SQLITE_ROW" : "SQLITE_ERROR");
- sqlite3_reset(stmt); /* 如果要重新绑定其他值要reset一下 */
- sqlite3_bind_int(stmt, 1, 201601008);
- sqlite3_bind_text(stmt, 2, "xiaowu", -1, NULL); /* 重新绑定值 */
- sqlite3_bind_text(stmt, 3, "yes", 3, NULL);
- sqlite3_step(stmt); /* 再执行 */
- /* 销毁prepare 创建的语句对象 */
- sqlite3_finalize(stmt);
- /* 取数据 */
- //sql = "select * from healthinfo;";
- sql = "select * from healthinfo limit 4 offset 2;"; /* 限制返回4行且从第3行开始 */
- sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);
- printf("total_column = %d\n", sqlite3_column_count(stmt));
- /* 遍历执行sql语句后的结果集的每一行数据 */
- while(sqlite3_step(stmt) == SQLITE_ROW){
- /* 获得字节数,第二个参数为select结果集合的列号 */
- /* 由于select 的结果集只有section这一列,因此为0 */
- int len_sid = sqlite3_column_bytes(stmt, 0);
- int len_name = sqlite3_column_bytes(stmt, 1);
- int len_ishealth = sqlite3_column_bytes(stmt, 2);
- printf("sid = %d, len = %d\n", sqlite3_column_int(stmt, 0), len_sid);
- printf("name = %s, len = %d\n", sqlite3_column_text(stmt, 1), len_name);
- printf("ishealth = %s, len = %d\n", sqlite3_column_text(stmt, 2), len_ishealth);
- //unsigned char* srcdata = sqlite3_column_blob(stmt, 0); /* 取得数据库中的blob数据 */
- }
- printf("\n");
- sqlite3_finalize(stmt);
- /******************* end ****************************/
- const char* data = "select call back function call!\n";
- /* select 使用*/
- sql = "select * from healthinfo where ishealth == 'yes';";
- rc = sqlite3_exec(db, sql, select_callback, data, &zErrMsg);
- if( rc != SQLITE_OK ){
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_free(zErrMsg);
- }else{
- fprintf(stdout, "Table select successfully\n");
- }
- data = "update call back function call!\n";
- /* update 使用*/
- sql = "update healthinfo set ishealth = 'no' where name='xiaoli';" \
- "select * from healthinfo where ishealth == 'yes';";
- rc = sqlite3_exec(db, sql, select_callback, data, &zErrMsg);
- if( rc != SQLITE_OK ){
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_free(zErrMsg);
- }else{
- fprintf(stdout, "Table update successfully\n");
- }
- /* 删除表 */
- sql = "drop table healthinfo;";
- rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);
- if( rc != SQLITE_OK ){
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_free(zErrMsg);
- }else{
- fprintf(stdout, "Table droped successfully\n");
- }
- char sql5[256];
- char* tname = "abc";
- sprintf(sql5, "create table if not exists %s ("\
- "id int not null," \
- "name text not null);", tname);
- printf("%s\n", sql5);
- /* 创建表 */
- rc = sqlite3_exec(db, sql5, NULL, NULL, &zErrMsg);
- if( rc != SQLITE_OK ){
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_free(zErrMsg);
- }else{
- fprintf(stdout, "Table created successfully\n");
- }
- sqlite3_close(db);
- }
相关阅读
1.下载sqlite3相关文件sqlite3.dll、sqlite3.h(可从http://download.csdn.net/detail/mingxia_sui/5249070下载),添加到工程的根目