sqlite_c_api
打开数据库
cpp
int sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
返回值:
- 成功:(0) SQLITE_OK https://www.sqlite.org/rescode.html#ok
- 失败:非0,并可通过sqlite3_errmsg()获取失败原因 https://www.sqlite.org/rescode.html https://www.sqlite.org/c3ref/errcode.html
执行SQLite语句
cpp
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 */
);
https://www.sqlite.org/c3ref/exec.html
参数详解:
参数1:传入已经打开的数据库指针
参数2:要执行的SQL语句
参数3:执行完SQL语句后的回调函数,查询语句能够查询出几条数据(也就是几行)就会调用几次回调函数。
void* arg
:参数4传入的参数int column
:查询的结果有几列char** value
:字段值char** name
:字段名
回调函数返回值为int类型,查询无误应返回0或SQLITE_OK,建议使用SQLITE_OK。
查询出的内容在回调函数中默认都是以字符串格式进行处理的,比如int类型的11,处理时是以字符串格式进行处理的。
参数4:可以给回调函数传一个参数
参数5:保存错误信息的,NULL
get_table
这是为了向后兼容而保留的传统接口。不建议使用此接口。
cpp
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);
关闭数据库
和文件操作一样,读写完毕后应该进行关闭操作。
cpp
int sqlite3_close(sqlite3*);
整体小示例
cpp
编译运行
shell
# 编译
$ gcc main.c -o main -lsqlite3
# 运行
$ ./main