当前位置: 移动技术网 > IT编程>数据库>SQLLite > SQLite教程(十四):C语言编程实例代码(2)

SQLite教程(十四):C语言编程实例代码(2)

2017年11月30日  | 移动技术网IT编程  | 我要评论

三、高效的批量数据插入:

    在给出操作步骤之前先简单说明一下批量插入的概念,以帮助大家阅读其后的示例代码。事实上,批量插入并不是什么新的概念,在其它关系型数据库的c接口api中都提供了一定的支持,只是接口的实现方式不同而已。纵观众多流行的数据库接口,如oci(oracle api)、mysql api和postgresql api等,oci提供的编程接口最为方便,实现方式也最为高效。sqlite作为一种简单灵活的嵌入式数据库也同样提供了该功能,但是实现方式并不像其他数据库那样方便明显,它只是通过一种隐含的技巧来达到批量插入的目的,其逻辑如下:

    1). 开始一个事物,以保证后面的数据操作语句均在该事物内完成。在sqlite中,如果没有手工开启一个事物,其所有的dml语句都是在自动提交模式下工作的,既每次操作后数据均被自动提交并写入磁盘文件。然而在非自动提交模式下,只有当其所在的事物被手工commit之后才会将修改的数据写入到磁盘中,之前修改的数据都是仅仅驻留在内存中。显而易见,这样的批量写入方式在效率上势必会远远优于多迭代式的单次写入操作。

    2). 基于变量绑定的方式准备待插入的数据,这样可以节省大量的sqlite3_prepare_v2函数调用次数,从而节省了多次将同一sql语句编译成sqlite内部识别的字节码所用的时间。事实上,sqlite的官方文档中已经明确指出,在很多时候sqlite3_prepare_v2函数的执行时间要多于sqlite3_step函数的执行时间,因此建议使用者要尽量避免重复调用sqlite3_prepare_v2函数。在我们的实现中,如果想避免此类开销,只需将待插入的数据以变量的形式绑定到sql语句中,这样该sql语句仅需调用sqlite3_prepare_v2函数编译一次即可,其后的操作只是替换不同的变量数值。

    3). 在完成所有的数据插入后显式的提交事物。提交后,sqlite会将当前连接自动恢复为自动提交模式。
   
    下面是示例代码的实现步骤:

    1). 创建测试数据表。
    2). 通过执行begin transaction语句手工开启一个事物。
    3). 准备插入语句及相关的绑定变量。
    4). 迭代式插入数据。
    5). 完成后通过执行commit语句提交事物。
    6). 删除测试表。
    见以下代码及关键性注释:

复制代码 代码如下:

#include <sqlite3.h>
#include <string>
#include <stdio.h>

using namespace std;

void dotest()
{
    sqlite3* conn = null;
    //1. 打开数据库
    int result = sqlite3_open("d:/mytest.db",&conn);
    if (result != sqlite_ok) {
        sqlite3_close(conn);
        return;
    }
    const char* createtablesql =
        "create table testtable (int_col int, float_col real, string_col text)";
    sqlite3_stmt* stmt = null;
    int len = strlen(createtablesql);
    //2. 准备创建数据表,如果创建失败,需要用sqlite3_finalize释放sqlite3_stmt对象,以防止内存泄露。
    if (sqlite3_prepare_v2(conn,createtablesql,len,&stmt,null) != sqlite_ok) {
        if (stmt)
            sqlite3_finalize(stmt);
        sqlite3_close(conn);
        return;
    }
    //3. 通过sqlite3_step命令执行创建表的语句。对于ddl和dml语句而言,sqlite3_step执行正确的返回值
    //只有sqlite_done,对于select查询而言,如果有数据返回sqlite_row,当到达结果集末尾时则返回
    //sqlite_done。
    if (sqlite3_step(stmt) != sqlite_done) {
        sqlite3_finalize(stmt);
        sqlite3_close(conn);
        return;
    }
    //4. 释放创建表语句对象的资源。
    sqlite3_finalize(stmt);
    printf("succeed to create test table now.\n");

    //5. 显式的开启一个事物。
    sqlite3_stmt* stmt2 = null;
    const char* beginsql = "begin transaction";
    if (sqlite3_prepare_v2(conn,beginsql,strlen(beginsql),&stmt2,null) != sqlite_ok) {
        if (stmt2)
            sqlite3_finalize(stmt2);
        sqlite3_close(conn);
        return;
    }
    if (sqlite3_step(stmt2) != sqlite_done) {
        sqlite3_finalize(stmt2);
        sqlite3_close(conn);
        return;
    }
    sqlite3_finalize(stmt2);

    //6. 构建基于绑定变量的插入数据。
    const char* insertsql = "insert into testtable values(?,?,?)";
    sqlite3_stmt* stmt3 = null;
    if (sqlite3_prepare_v2(conn,insertsql,strlen(insertsql),&stmt3,null) != sqlite_ok) {
        if (stmt3)
            sqlite3_finalize(stmt3);
        sqlite3_close(conn);
        return;
    }
    int insertcount = 10;
    const char* strdata = "this is a test.";
    //7. 基于已有的sql语句,迭代的绑定不同的变量数据
    for (int i = 0; i < insertcount; ++i) {
        //在绑定时,最左面的变量索引值是1。
        sqlite3_bind_int(stmt3,1,i);
        sqlite3_bind_double(stmt3,2,i * 1.0);
        sqlite3_bind_text(stmt3,3,strdata,strlen(strdata),sqlite_transient);
        if (sqlite3_step(stmt3) != sqlite_done) {
            sqlite3_finalize(stmt3);
            sqlite3_close(conn);
            return;
        }
        //重新初始化该sqlite3_stmt对象绑定的变量。
        sqlite3_reset(stmt3);
        printf("insert succeed.\n");
    }
    sqlite3_finalize(stmt3);

    //8. 提交之前的事物。
    const char* commitsql = "commit";
    sqlite3_stmt* stmt4 = null;
    if (sqlite3_prepare_v2(conn,commitsql,strlen(commitsql),&stmt4,null) != sqlite_ok) {
        if (stmt4)
            sqlite3_finalize(stmt4);
        sqlite3_close(conn);
        return;
    }
    if (sqlite3_step(stmt4) != sqlite_done) {
        sqlite3_finalize(stmt4);
        sqlite3_close(conn);
        return;
    }
    sqlite3_finalize(stmt4);

    //9. 为了方便下一次测试运行,我们这里需要删除该函数创建的数据表,否则在下次运行时将无法
    //创建该表,因为它已经存在。
    const char* dropsql = "drop table testtable";
    sqlite3_stmt* stmt5 = null;
    if (sqlite3_prepare_v2(conn,dropsql,strlen(dropsql),&stmt5,null) != sqlite_ok) {
        if (stmt5)
            sqlite3_finalize(stmt5);
        sqlite3_close(conn);
        return;
    }
    if (sqlite3_step(stmt5) == sqlite_done) {
        printf("the test table has been dropped.\n");
    }
    sqlite3_finalize(stmt5);
    sqlite3_close(conn);
}

int main()
{
    dotest();
    return 0;
}
//输出结果如下:
//succeed to create test table now.
//insert succeed.
//insert succeed.
//insert succeed.
//insert succeed.
//insert succeed.
//insert succeed.
//insert succeed.
//insert succeed.
//insert succeed.
//insert succeed.
//the test table has been dropped.

 该结果和上一个例子(普通数据插入)的结果完全相同,只是在执行效率上明显优于前者。

四、数据查询:

    数据查询是每个关系型数据库都会提供的最基本功能,下面的代码示例将给出如何通过sqlite api获取数据。
    1). 创建测试数据表。
    2). 插入一条测试数据到该数据表以便于后面的查询。
    3). 执行select语句检索数据。
    4). 删除测试表。
    见以下示例代码和关键性注释:

复制代码 代码如下:

#include <sqlite3.h>
#include <string>
#include <stdio.h>

using namespace std;

void dotest()
{
    sqlite3* conn = null;
    //1. 打开数据库
    int result = sqlite3_open("d:/mytest.db",&conn);
    if (result != sqlite_ok) {
        sqlite3_close(conn);
        return;
    }
    const char* createtablesql =
        "create table testtable (int_col int, float_col real, string_col text)";
    sqlite3_stmt* stmt = null;
    int len = strlen(createtablesql);
    //2. 准备创建数据表,如果创建失败,需要用sqlite3_finalize释放sqlite3_stmt对象,以防止内存泄露。
    if (sqlite3_prepare_v2(conn,createtablesql,len,&stmt,null) != sqlite_ok) {
        if (stmt)
            sqlite3_finalize(stmt);
        sqlite3_close(conn);
        return;
    }
    //3. 通过sqlite3_step命令执行创建表的语句。对于ddl和dml语句而言,sqlite3_step执行正确的返回值
    //只有sqlite_done,对于select查询而言,如果有数据返回sqlite_row,当到达结果集末尾时则返回
    //sqlite_done。
    if (sqlite3_step(stmt) != sqlite_done) {
        sqlite3_finalize(stmt);
        sqlite3_close(conn);
        return;
    }
    //4. 释放创建表语句对象的资源。
    sqlite3_finalize(stmt);
    printf("succeed to create test table now.\n");

    //5. 为后面的查询操作插入测试数据。
    sqlite3_stmt* stmt2 = null;
    const char* insertsql = "insert into testtable values(20,21.0,'this is a test.')";
    if (sqlite3_prepare_v2(conn,insertsql,strlen(insertsql),&stmt2,null) != sqlite_ok) {
        if (stmt2)
            sqlite3_finalize(stmt2);
        sqlite3_close(conn);
        return;
    }
    if (sqlite3_step(stmt2) != sqlite_done) {
        sqlite3_finalize(stmt2);
        sqlite3_close(conn);
        return;
    }
    printf("succeed to insert test data.\n");
    sqlite3_finalize(stmt2);

    //6. 执行select语句查询数据。
    const char* selectsql = "select * from testtable";
    sqlite3_stmt* stmt3 = null;
    if (sqlite3_prepare_v2(conn,selectsql,strlen(selectsql),&stmt3,null) != sqlite_ok) {
        if (stmt3)
            sqlite3_finalize(stmt3);
        sqlite3_close(conn);
        return;
    }
    int fieldcount = sqlite3_column_count(stmt3);
    do {
        int r = sqlite3_step(stmt3);
        if (r == sqlite_row) {
            for (int i = 0; i < fieldcount; ++i) {
                //这里需要先判断当前记录当前字段的类型,再根据返回的类型使用不同的api函数
                //获取实际的数据值。
                int vtype = sqlite3_column_type(stmt3,i);
                if (vtype == sqlite_integer) {
                    int v = sqlite3_column_int(stmt3,i);
                    printf("the integer value is %d.\n",v);
                } else if (vtype == sqlite_float) {
                    double v = sqlite3_column_double(stmt3,i);
                    printf("the double value is %f.\n",v);
                } else if (vtype == sqlite_text) {
                    const char* v = (const char*)sqlite3_column_text(stmt3,i);
                    printf("the text value is %s.\n",v);
                } else if (vtype == sqlite_null) {
                    printf("this value is null.\n");
                }
            }
        } else if (r == sqlite_done) {
            printf("select finished.\n");
            break;
        } else {
            printf("failed to select.\n");
            sqlite3_finalize(stmt3);
            sqlite3_close(conn);
            return;
        }
    } while (true);
    sqlite3_finalize(stmt3);

    //7. 为了方便下一次测试运行,我们这里需要删除该函数创建的数据表,否则在下次运行时将无法
    //创建该表,因为它已经存在。
    const char* dropsql = "drop table testtable";
    sqlite3_stmt* stmt4 = null;
    if (sqlite3_prepare_v2(conn,dropsql,strlen(dropsql),&stmt4,null) != sqlite_ok) {
        if (stmt4)
            sqlite3_finalize(stmt4);
        sqlite3_close(conn);
        return;
    }
    if (sqlite3_step(stmt4) == sqlite_done) {
        printf("the test table has been dropped.\n");
    }
    sqlite3_finalize(stmt4);
    sqlite3_close(conn);
}

int main()
{
    dotest();
    return 0;
}
//输出结果如下:
//succeed to create test table now.
//succeed to insert test data.
//the integer value is 20.
//the double value is 21.000000.
//the text value is this is a test..
//select finished.
//the test table has been dropped.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网