欢迎投稿

今日深度:

持久化存储 (SQLite),化存储sqlite

持久化存储 (SQLite),化存储sqlite


SQLite 是iOS集成的一个轻量级的数据库。请注意:sqlite只是一个嵌入式的数据库引擎,实际上就是一个文件。不需要安装,启动服务等操作。

1、Xcode6 导入libsqlite3.dylib,如图(和导入其他的库一样) ;libsqlite3总代表最近版本的SQLite3,所以选择libsqlite3.dylib就ok了



2、常用函数:

(1)  创建数据库函数:

SQLITE_API int sqlite3_open(

  const char *filename,   /* Database filename (UTF-8) */

  sqlite3 **ppDb          /* OUT: SQLite db handle */

);

解释:打开与filename文件关联的数据库连接,并让ppDb参数引用被打开的数据库连接,如果filename文件不存在,系统会自动创建。创建成功返回0;

   (2) 执行没有返回值的sql语句的函数(一般创建表的时候使用)

SQLITE_API 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 */

);

解释:用于执行没有返回值的sql语句;第一个参数代表打开的数据库连接,第二个参数为要执行的sql语句,第三个参 数为执行完成的回调函数,第四个参数为传给回调函数的参数,第五个用于sql语句出错后的错误信息。

  (3)对sql语句执行预编译函数

SQLITE_API int sqlite3_prepare(

  sqlite3 *db,            /* Database handle */

  const char *zSql,       /* SQL statement, UTF-8 encoded */

  int nByte,              /* Maximum length of zSql in bytes. */

  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */

  const char **pzTail     /* OUT: Pointer to unused portion of zSql */

);

解释:对sql语句执行预编译,第一个参数代表打开的数据库的连接,第二个参数代表sql语句,第三个参数代表sql语句的最大长度,一般设为-1,第四个参数为传出参数指向预编译sql语句产生的sqlite3_stmt,第五个参数为指向sql未使用的部分。

  (4)绑定参数函数

SQLITE_API int sqlite3_bind_XXX(sqlite3_stmt*, int, const char*, int n, void(*)(void*)) ;

解释:XXX代表类型。同于sqlite3_stmt中占位符参数绑定参数,第一个参数的索引为1往后索引逐个加1.第一个参数为预编译的sql语句,第二个参数为参数的索引,第三个为参数绑定的值,后边直接传-1和NUll就好了。

  (5)sql执行语句

SQLITE_API int sqlite3_step(sqlite3_stmt*);

解释:用于执行sql语句,如果函数返回为SQLITE_DONE,表示该函数执行成功。除非调用sqlite3_reset()函数来重新设置sqlite3_stmt,否则不应该再次调用此函数。如果该函数返回SQLITE_ROW,表示sqlite3_stmt正在逐行提取查询结果集,可以重复调用sqlite3_step函数,直到不再返回SQLITE_ROW。

(6)返回当前行制定列的数据

SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);

解释:第一个参数为sqlite3_stmt,第二个参数为列号(从0开始)

       (7)销毁sqlite3_stmt,并收回资源

SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);

注意:在关闭数据库之前如果使用了预编译执行sql语句,就执行该函数

(8)关闭数据库

SQLITE_API int sqlite3_close(sqlite3*);


3、看下面的实例代码

#pragma mark - 添加单词

- (IBAction)addWord:(id)sender {

    //插入数据

    NSString *word = self.wordTF.text;

    NSString *detail = self.detailTF.text;

    //创建数据库

    if (word != nil && word.length > 0 && detail != nil && detail.length > 0) {

        //1、创建数据库

        sqlite3 *dataBase;

        sqlite3_open([[self dbPath] UTF8String], &dataBase);

        

        //2、创建表

        //定义错误字符串

        char *errMsg;

        //定义执行的SQL语句

        const char *createSql = "create table if not exists word_inf \

        (_id integer primary key autoincrement,\

        word text,\

        detail text)"; //worddetail可以定义类型也可以不定义,sqlite会根据类型推断

        //执行创建表的语句,执行没有返回值的SQL语句用

        NSLog(@"创建表的语句:%@",[NSString stringWithUTF8String:createSql]);

        int result = sqlite3_exec(dataBase, createSql, NULL, NULL, &errMsg);

//        NSFileManager *fileManager = [NSFileManager defaultManager];

        if (result == SQLITE_OK) {  //执行成功

            const char *insertSQL = "insert into word_inf values(null,?,?)";

            // 预编译SQL语句,stmt变量保存了预编译结果的指针

            sqlite3_stmt *stmt;

            int insertResult = sqlite3_prepare(dataBase, insertSQL, -1, &stmt, NULL);

            //如果编译成功

            if (insertResult == SQLITE_OK) {

                

                //为第一个?占位符绑定参数

                sqlite3_bind_text(stmt, 1, [word UTF8String], -1, NULL);

                //为第二个?占位符绑定参数

                sqlite3_bind_text(stmt, 2, [detail UTF8String], -1, NULL);

                

                //执行Sql

                sqlite3_step(stmt);

                

                //清空输入框中的内容

                self.wordTF.text = @"";

                self.detailTF.text = @"";

                

            }

            sqlite3_finalize(stmt);

        }

        //关闭数据库

        sqlite3_close(dataBase);

        

    }

}

#pragma mark - 读取数据库,segue传值

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

    //读取数据

    NSString *key = self.keyTF.text;

    if (key != nil && key.length > 0 ) {

        //打开数据库

        sqlite3 *dataBase;

        sqlite3_open([[self dbPath] UTF8String], &dataBase);

        

        //预编译SQL

        const char *selectSQL = "select * from word_inf  where word like ?";

        sqlite3_stmt *stmt;

        int queryResult = sqlite3_prepare(dataBase, selectSQL, -1, &stmt, NULL);

        if (queryResult == SQLITE_OK) {

            //绑定占位符

            sqlite3_bind_text(stmt, 1, [[NSString stringWithFormat:@"%%%@%%",key] UTF8String], -1, NULL);

            //采用循环多次执行sqlite3_step()函数,并从中取出查询结果

            while (sqlite3_step(stmt) == SQLITE_ROW) {

                int word_id = sqlite3_column_int(stmt, 0);

                char *word = (char *)sqlite3_column_text(stmt, 1);

                char *detail = (char *)sqlite3_column_text(stmt, 2);

                

                //绑定到模型

                NKWord *wordObj = [[NKWord alloc]initWithId:word_id word:[NSString stringWithUTF8String:word] detail:[NSString stringWithUTF8String:detail]];

                [self.resultArray addObject:wordObj];

            }

        }

        // 关闭数据库

        sqlite3_close(dataBase);

        

        //跳转

        DetailWordController *detailWordVc = (DetailWordController *)segue.destinationViewController;

        detailWordVc.wordArray = self.resultArray;

        

        

    }

    


}



www.htsjk.Com true http://www.htsjk.com/SQLite/33980.html NewsArticle 持久化存储 (SQLite),化存储sqlite SQLite 是iOS集成的一个轻量级的数据库。请注意:sqlite只是一个嵌入式的数据库引擎,实际上就是一个文件。不需要安装,启动服务等操作。 1、Xcod...
相关文章
    暂无相关文章
评论暂时关闭