博客> iOS 源生SQLite3 “增改删查”(Objective-C)
iOS 源生SQLite3 “增改删查”(Objective-C)
2017-05-25 09:53 评论:0 阅读:160 ichampion
ios sqlite3

刚入行,属于自学加独立开发,所以记录一下自己写过的东西,大神看见了还请指点指点

SQLite可视化工具:SQLite Professional SQLite Professional

新建Project,添加SQLite3库文件 Lib

因为是Demo,所以一切从简,只实现最简单的操作 首先定义一个全局的句柄

static sqlite3 * db = nil;  //设置句柄 通过句柄对数据库进行操作

打开数据库连接,并且创建表格

-(void)openDB{

    NSArray *test = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    /*
     directory 目录类型 比如Documents目录 就是NSDocumentDirectory
     domainMask 在iOS的程序中这个取NSUserDomainMask
     expandTilde YES,表示将~展开成完整路径
     */
    NSString * fileName = [[test lastObject]stringByAppendingPathComponent:@"DB_ichampion.sqlite"];
    // lastObject 取NSSearchPathForDirectoriesInDomains数组最后一个元素

    NSLog(@"%@",fileName);
    //打开数据库 如果没有打开的数据库就建立一个
    //第一个参数是数据库的路径 注意要转换为c的字符串
    if (sqlite3_open(fileName.UTF8String, &db) == SQLITE_OK) {
        NSLog(@"打开数据库成功");
        //打开数据库成功后建立数据库内的表
        //操作命令的字符串
        //注意SQL语句结束处有 ; 号
        NSString * sql = @"create table if not exists Table_ichampion (id integer primary key autoincrement,name text,age intger);";
        char * err;
        sqlite3_exec(db, sql.UTF8String, NULL, NULL, &err);
        if (err) {
            NSLog(@"建表失败 -- %s",err);
        }else{
            NSLog(@"建表成功");
        }
    }else{
        NSLog(@"打开数据库失败");
    }
}

运行完成以后,打印输出SQLite文件路径,通过路径查找到.SQLite文件,用SQLite Professional打开 Create

可以看到表格就算新建好了 创建完表格则需要插入数据,这里一共插入了4条记录,但是总的来说写法就两大种,前面三条记录只是SQL语句的不同

-(void)insertDB{
    char * err;

    NSString * sql = @"insert into Table_ichampion(id,name,age) values(1,'Zhan',18);";
    printf("%d",sqlite3_exec(db, sql.UTF8String, NULL, NULL, &err));

    NSString * sql1 = @"insert into Table_ichampion(id,name,age) values(3,'Michael',8);";
    sqlite3_exec(db, sql1.UTF8String, NULL, NULL, &err);

    NSString * sql2 = @"insert into Table_ichampion values(NULL,'abc',6);";
    sqlite3_exec(db, sql2.UTF8String, NULL, NULL, &err);

    NSString * tableName = @"Table_ichampion";
    NSString * Name = @"name";
    NSString * Age = @"age";
    NSString * NameValue = @"abcd";
    int AgeValue = 3;
    NSString *sql3 = [NSString stringWithFormat:@"INSERT INTO '%@' ('%@', '%@', '%@') VALUES('%d', '%@', '%d')", tableName, @"id", Name, Age, 5, NameValue, AgeValue];
    if (sqlite3_exec(db, [sql3 UTF8String], NULL, NULL, &err) != SQLITE_OK)
    {
        NSAssert(0, @"插入数据错误!");
    }
}

同样,我们可以看一下运行结果 insert

接下来是数据修改,这里选择id为5的记录 name 更改为 xyz

-(void)updateDB{
    //id为5的记录 name 更改为 xyz
        NSString * sql = @"update Table_ichampion set name = 'xyz' where id = 5;";
        char * err;
        sqlite3_exec(db, sql.UTF8String, NULL, NULL, &err);
        if (err) {
            NSLog(@"修改失败--%s",err);
        }else{
            NSLog(@"修改成功");
        }
}

修改完成 update

然后是删除,这里删除 abc 这条记录

-(void)deleteDB{
//    删除 name = abc 的记录
    NSString * sql = @"DELETE FROM Table_ichampion WHERE name = 'abc';";
    char * err;
    sqlite3_exec(db, sql.UTF8String, NULL, NULL, &err);
    if (err) {
        NSLog(@"删除失败--%s",err);
    }else{
        NSLog(@"删除成功");
    }
}

然后直接查看,看看是否删除了abc这条记录,以及数据库中数据是否如截图所示那样(这里查看分整张表格查看和单条记录查看两种)

-(void)selectDB{
    NSString *sql = @"SELECT * FROM Table_ichampion";
    sqlite3_stmt *statement;
//    查询整张表格
    if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW) {

            char *id = (char *)sqlite3_column_text(statement, 0);
            NSString *idStr = [[NSString alloc] initWithUTF8String:id];

            char *name = (char *)sqlite3_column_text(statement, 1);
            NSString *nameStr = [[NSString alloc] initWithUTF8String:name];

            char *age = (char *)sqlite3_column_text(statement, 2);
            NSString *ageStr = [[NSString alloc] initWithUTF8String:age];

            NSString *info = [[NSString alloc] initWithFormat:@"%@ - %@ - %@",
                              idStr, nameStr, ageStr];

            NSLog(@"%@",info);
        }
//     单条记录查询
        NSString *sql1 = @"SELECT * FROM Table_ichampion WHERE name = 'Zhan';";
        if (sqlite3_prepare_v2(db, [sql1 UTF8String], -1, &statement, nil) == SQLITE_OK) {
            while (sqlite3_step(statement) == SQLITE_ROW) {

                char *id = (char *)sqlite3_column_text(statement, 0);
                NSString *idStr = [[NSString alloc] initWithUTF8String:id];

                char *name = (char *)sqlite3_column_text(statement, 1);
                NSString *nameStr = [[NSString alloc] initWithUTF8String:name];

                char *age = (char *)sqlite3_column_text(statement, 2);
                NSString *ageStr = [[NSString alloc] initWithUTF8String:age];

                NSString *info = [[NSString alloc] initWithFormat:@"%@ - %@ - %@",
                                  idStr, nameStr, ageStr];

                NSLog(@"%@",info);
            }
        }
        sqlite3_finalize(statement);
        /*
        sqlite3_finalize
        这个过程销毁前面被sqlite3_prepare创建的准备语句,每个准备语句都必须使用这个函数去销毁以防止内存泄露。
        在空指针上调用这个函数没有什么影响,同时可以准备语句的生命周期的任一时刻调用这个函数:在语句被执行前,一次或多次调用sqlite_reset之后,或者在sqlite3_step任何调用之后不管语句是否完成执行
        sqlite3_close
        这个过程关闭前面使用sqlite3_open打开的数据库连接,任何与这个连接相关的准备语句必须在调用这个关闭函数之前被释放
        */
    }
}

select

可以看到少了一条记录,并且其他记录保持不变 最后,对比一下SQLite Professional的截图 SQL2

最后是访问数据库的返回值,其中0代表没有错误。我们可以用printf的方法来打印返回值,方便调试。

printf("CreateResult == %d\n",sqlite3_exec(db, sql.UTF8String, NULL, NULL, &err));
#define SQLITE_OK           0   /* Successful result */
/* beginning-of-error-codes */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
#define SQLITE_PERM         3   /* Access permission denied */
#define SQLITE_ABORT        4   /* Callback routine requested an abort */
#define SQLITE_BUSY         5   /* The database file is locked */
#define SQLITE_LOCKED       6   /* A table in the database is locked */
#define SQLITE_NOMEM        7   /* A malloc() failed */
#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
#define SQLITE_FULL        13   /* Insertion failed because database is full */
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
#define SQLITE_EMPTY       16   /* Database is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
#define SQLITE_MISMATCH    20   /* Data type mismatch */
#define SQLITE_MISUSE      21   /* Library used incorrectly */
#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define SQLITE_AUTH        23   /* Authorization denied */
#define SQLITE_FORMAT      24   /* Auxiliary database format error */
#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
#define SQLITE_NOTADB      26   /* File opened that is not a database file */
#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
/* end-of-error-codes */

工程源码http://download.csdn.net/detail/u012138272/9588703


参考资料:http://www.cnblogs.com/hanjun/archive/2012/10/29/2744573.html

收藏
0
sina weixin mail 回到顶部