Sqlite3 C语言 应用

1.打开数据库链接sqlite3_open用法

原型:

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

用这个函数开始数据库操作。需要传入两个参数,一是数据库文件名,比如:E:/test.db。文件名不需要一定存在,如果此文件不存在,sqlite会自动建立它。如果它存在,就尝试把它当数据库文件来打开。二是sqlite3**,即前面提到的关键数据结构。这个结构底层细节如何,你不要管它。 函数返回值表示操作是否正确,如果是SQLITE_OK则表示操作正常。相关的返回值sqlite定义了一些宏。具体这些宏的含义可以参考sqlite3.h 文件。里面有详细定义(顺便说一下,sqlite3 的代码注释率自称是非常高的,实际上也的确很高。只要你会看英文,sqlite 可以让你学到不少东西)。

2。关闭数据库链接sqlite3_close用法

原型:

int sqlite3_close(sqlite3 *ppDb);
 

ppDb为刚才使用sqlite3_open打开的数据库链接

3.执行sql操作sqlite3_exec用法

原型:

1 int sqlite3_exec(
2   sqlite3* ppDb,                             /* An open database */
3   const char *sql,                           /* SQL to be evaluated */
4   int (*callback)(void*,int,char**,char**),  /* Callback function */
5   void *,                                    /* 1st argument to callback */
6   char **errmsg                              /* Error msg written here */
7 );

这就是执行一条sql 语句的函数。 第1个参数不再说了,是前面open函数得到的指针。说了是关键数据结构。 第2个参数constchar*sql是一条sql 语句,以结尾。 第3个参数sqlite3_callback 是回调,当exec这条语句执行之后,sqlite3会去调用你提供的这个函数。 第4个参数void*是你所提供的指针,你可以传递任何一个指针参数到这里,这个参数最终会传到回调函数里面,如果不需要传递指针给回调函数,可以填NULL。等下我们再看回调函数的写 法,以及这个参数的使用。 第5个参数char** errmsg 是错误信息。注意是指针的指针。sqlite3里面有很多固定的错误信息。执行sqlite3_exec 之后,执行失败时可以查阅这个指针(直接cout<<errmsg得到一串字符串信息,这串信息告诉你错在什么地方。sqlite3_exec函数通过修改你传入的指针的指针,把你提供的指针指向错误提示信息,这样sqlite3_exec函数外面就可以通过这个char*得到具体错误提示。
说明:通常,sqlite3_callback 和它后面的void*这两个位置都可以填NULL。填NULL表示你不需要回调。比如你做insert 操作,做delete操作,就没有必要使用回调。而当你做select 时,就要使用回调,因为sqlite3 把数据查出来,得通过回调告诉你查出了什么数据。

4.exec 的回调

typedef int(*sqlite3_callback)(void*,int,char**,char**); 你的回调函数必须定义成上面这个函数的类型。下面给个简单的例子: //sqlite3的回调函数 //sqlite 每查到一条记录,就调用一次这个回调 int LoadMyInfo(void* para,intn_column,char** column_value,char** column_name);

//para是你在sqlite3_exec 里传入的void*参数通过para参数,你可以传入一些特殊的指针(比如类指针、结构指针), //然后在这里面强制转换成对应的类型(这里面是void*类型,必须强制转换成你的类型才可用)。然后操作这些数据 //n_column是这一条记录有多少个字段(即这条记录有多少列) //char** column_value 是个关键值,查出来的数据都保存在这里,它实际上是个1维数组(不要以为是2维数组), //每一个元素都是一个char*值,是一个字段内容(用字符串来表示,以结尾) //char** column_name 跟column_value是对应的,表示这个字段的字段名称

实例:

1 #include <iostream>
 2 using namespace std;
 3 #include "sqlite/sqlite3.h"
 4 int callback(void*,int,char**,char**);
 5 int main()
 6 {
 7     sqlite3* db;
 8     int nResult = sqlite3_open("test.db",&db);
 9     if (nResult != SQLITE_OK)
10     {
11         cout<<"打开数据库失败:"<<sqlite3_errmsg(db)<<endl;
12         return 0;
13     }
14     else
15     {
16         cout<<"数据库打开成功"<<endl;
17     }
18 
19     char* errmsg;
20 
21     nResult = sqlite3_exec(db,"create table fuck(id integer primary key autoincrement,name varchar(100))",NULL,NULL,&errmsg);
22      if (nResult != SQLITE_OK)
23      {
24          sqlite3_close(db);
25          cout<<errmsg;
26          sqlite3_free(errmsg);
27         return 0;
28     }
29     string strSql;
30     strSql+="begin;
";
31     for (int i=0;i<100;i++)
32     {
33         strSql+="insert into fuck values(null,'heh');
";
34     }
35     strSql+="commit;";
36     //cout<<strSql<<endl;
37 
38     nResult = sqlite3_exec(db,strSql.c_str(),NULL,NULL,&errmsg);
39 
40     if (nResult != SQLITE_OK)
41     {
42         sqlite3_close(db);
43         cout<<errmsg<<endl;
44         sqlite3_free(errmsg);
45         return 0;
46     }
47 
48     strSql = "select * from fuck";
49     nResult = sqlite3_exec(db,strSql.c_str(),callback,NULL,&errmsg);
50       if (nResult != SQLITE_OK)
51     {
52         sqlite3_close(db);
53         cout<<errmsg<<endl;
54         sqlite3_free(errmsg);
55         return 0;
56     }
57 
58     sqlite3_close(db);
59     return 0;
60 }
61 
62 int callback(void* ,int nCount,char** pValue,char** pName)
63 {
64     string s;
65     for(int i=0;i<nCount;i++)
66     {
67         s+=pName[i];
68         s+=":";
69         s+=pValue[i];
70         s+="
";
71     }
72     cout<<s<<endl;
73     return 0;
74 }

Sqlite3函数调用返回值列表

Result Codes
#define SQLITE_OK           0   /* Successful result */
/* beginning-of-error-codes */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* 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 sqlite3_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   /* Unknown opcode in sqlite3_file_control() */
#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   /* Database is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
#define SQLITE_CONSTRAINT  19   /* Abort due to constraint 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_FORMAT      24   /* Auxiliary database format error */
#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
#define SQLITE_NOTADB      26   /* File opened that is not a database file */
#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
/* end-of-error-codes */
 
Extended Result Codes
#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
 
 
Conflict resolution modes
#define SQLITE_ROLLBACK 1
/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
#define SQLITE_FAIL     3
/* #define SQLITE_ABORT 4  // Also an error code */
#define SQLITE_REPLACE  5
These constants are returned by sqlite3_vtab_on_conflict() to inform a virtual table implementation what the ON CONFLICT mode is for the SQL statement being evaluated.
原文地址:https://www.cnblogs.com/muzijinshui/p/3446620.html