sqlite & C

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);

记住最后释放资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值