码迷,mamicode.com
首页 > 移动开发 > 详细

iOS学习笔记16-SQLite应用

时间:2016-02-23 13:00:27      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

 /**

     *

     

     应用数据库步骤:

     1,sqlite3_open:打开或者创建数据库并做连接操作

     2,用sql语句,创建数据库

     3,无返回值时,用exec语句操作执行数据库语句

     4,有返回值时,用prepare语句查询函数,结果集遍历得到结果,遍历语句sqlite_step(stmt) == SQLITE_ROW

     5,将记录中的字段解成字句 sqlite_column_XXX (结果集,字段的索引值)

     **/

 

 

 

技术分享首先引用sqlite3数据库文件

 

取到文件夹路径

 NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

    NSLog(@"%@",document);

 

要创建数据库的路径

    NSString *dbFilePath = [document stringByAppendingString:@"/db.sqlite"];

 

  /**

     *创建数据库

     **/

 sqlite3 *db;//与底层数据库的连接

    if (sqlite3_open([dbFilePath UTF8String], &db) == SQLITE_OK) {//打开数据库成功选择宏的名字//此处表示创建成功

        NSLog(@"创建数据库成功");

    }

/**

     *在数据库里面添加数据

     **/

    NSString *createTableSql = @"create table Stu3(id integer primary key autoincrement,name text,password text)";//创建表的sq语句

    if(sqlite3_exec(db, [createTableSql UTF8String], NULL, NULL, NULL) == SQLITE_OK)

    {

           NSLog(@"创建表成功");

       }//执行创建表的语句

    

/**

     *插入数据

     **/

    NSString *insertSql = @"insert into Stu3(name,password) values(‘hahah‘,‘567‘)";//插入数据的字符串

    if ( sqlite3_exec(db, [insertSql UTF8String], NULL, NULL, NULL) == SQLITE_OK) {

        NSLog(@"执行插入语句成功");

    }

 

/**

     *插入多条数据

     用户名 dsn1-10

     密码 六位数字

     **/

    for (int i = 0; i<10; i++) {

        insertSql = [NSString stringWithFormat:@"insert into Stu3(name,password) values(‘dsn%d‘,‘%06d‘)",i+1,arc4random()%100000];

//        NSLog(@"%@",insertSql);

        

        

        if (sqlite3_exec(db, [insertSql UTF8String], NULL, NULL, NULL)==SQLITE_OK) {

            NSLog(@"插入多条数据成功");

        }

        

    }

 

  /**

     *查询语句

     **/

    NSString *selectSql = @"select *from Stu3";

    sqlite3_stmt *stmt;//第四个参数 返回结果集

    sqlite3_prepare_v2(db, [selectSql UTF8String], -1, &stmt, NULL);//执行有返回值的SQL语句

    //遍历结果集//把结果集一行行拿出来//宏表示如果行存在就一直做查询

    while (sqlite3_step(stmt) == SQLITE_ROW) {

        int stu3Id = sqlite3_column_int(stmt, 0);

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

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

        

        NSLog(@"id=%d,name=%s,password=%s",stu3Id,stu3Name,stu3PassWord);

    }

 

结果:

技术分享

 

iOS学习笔记16-SQLite应用

标签:

原文地址:http://www.cnblogs.com/adodo/p/5209227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!