sqlite
- 优点: 轻量化的、单文件
- 缺点: 数据量较大时难以高效处理 -> mysql
SQL基本操作
CREATE TABLE <tablename> (<col1name> <col1type> [NOT NULL], <col2name>...)
/*
type: TEXT, INTEGER, NUMBER ...
TEXT用单/双引号包括
*/
INSERT INTO <tablename> VALUES (<col1value>, <col2value>...)
DELETE FROM <tablename> WHERE <condition1 AND condition2 OR condition3>
UPDATE <tablename> SET <somecolname> = <newcolvalue> WHERE <conditions>
SELECT <somecolname> FROM <tablename> WHERE <conditions>
sqlite shell
- 编译时包括shell.c得到shell.exe
元命令
-
元命令均以
.
开始,如.help
..help
.open <filename.db> – 打开或创建数据库
.tables – 列出所有的table
一句sql命令以 ;
结尾
Clang APIs
注:此处仅使用了包含原文件的使用方式,并未使用动态链接库,并无影响
#include "sqlite3.h"
sqlite3.h
中几乎所有的函数都有整型的返回值,标示 操作是否成功 ,后文以result
接收此值。
若成功执行操作,result
值为宏SQLITE_OK
.
打开/创建 & 关闭数据库
打开:相当于原命令 .open
sqlite3* db;
int result = sqlite3_open(path, &db);
int result = sqlite3_close(db);
执行sql命令
- sql语句应以
const char*
格式传递,在c环境下string
格式不受支持。 - 不需以
;
结尾
有回调函数
int sqlite3_exec(
sqlite3 *db, /* 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 */
);
// ex.
int result = sqlite3_exec(db, sql, NULL, NULL, NULL);
-
db: .db 数据库
-
*sql:sql语句
-
*callback:回调函数
形式固定:int callback(void*, int, char**, char**); int callback(void *param, int columnnum, char **column_val, char **column_name);
无回调函数
int sqlite3_get_table(sqlite3 *db, /* An open database */
const char *sql, /* SQL to be evaluated */
char ***azResult, /* Results of the query */
int *nRow, /* Number of result rows written here */
int *nColumn, /* Number of result columns written here */
char **errMsg /* Error msg written here */
);
// ex.
char **azresult;
int result = sqlite3_get_table(this->db, sql, &azresult, NULL, NULL, NULL);
sqlite3_free_table(azresult);
记住最后释放资源