SQLite - 接口使用

2020-01-09  本文已影响0人  Coc0

一、概要

本文简要介绍SQLite3C/C++接口,详细用法参考各节链接。

以下是SQLite重要的2种对象:

以下是SQLite重要的8种对外方法:

二、对象

2.1.sqlite3 - Database Connection Handle

sqlite3结构体用于描述sqlite数据库文件,类似于文件句柄。

2.2.sqlite3_stmt - Prepared Statement Object

sqlite3_stmt结构体用于描述编译后SQL语句。

形如,gcc会将.c文件编译为.o文件(处理器可执行二进制码),sqlite前端会将SQL语句编译为sqlite3_stmt结构体(SQLite引擎可执行代码)。

sqlite3_stmt的生命周期如下:

  1. 使用sqlite3_prepre_v2()函数创建sqlite3_stmt结构体。

  2. 使用sqlite3_bind_*()函数绑定参数。

  3. 使用一次/多次sqlite3_step()函数执行SQL语句。

  4. 使用sqlite3_reset()函数重设sqlite3_stmt,回到步骤2

  5. 析构sqlite3_stmt结构体。

三、接口

3.1.sqlite3_open()

sqlite3_open()函数用于创建与数据库文件的连接并返回sqlite3结构体。

使用实例:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="c++" cid="n1027" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">sqlite3 *db = NULL;
int err = sqlite3_open(argv[1], &db);
if(SQLITE_OK != err) {
printf("error open sqlite database\n");
exit(1);
}</pre>

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="c++" cid="n1032" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">const char* sql = "SELECT * FROM t WHERE y=?";
const char* ret = "";
sqlite3_stmt *stmt = NULL;
err = sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, &ret);
if(SQLITE_OK != err) {
printf("error construct sqlite3_stmt\n");
exit(1);
}</pre>

sqlite3_bind()函数用于绑定SQL语句中的参数,替换SQL语句形如(NNN - 整数,VVV - 参数名):

3.3.sqlite3_bind()

使用实例:

该函数不实际执行SQL语句,仅编译SQL语句,为执行准备。

sqlite3_prepare()函数用于编译SQL语句为sqlite3_stmt结构体。

3.2.sqlite3_prepare()

上一篇 下一篇

猜你喜欢

热点阅读