FMDB使用

作者: 答案在风中飘 | 来源:发表于2018-06-08 09:55 被阅读34次

看了很多别人的文章, 发现都是不知道谁复制谁, 作者自己根本不知道自己在说什么, 全是复制的。 也不知道这些人怎么想的 。废话不多说直接上代码

首先我是pod 导入的FMDB pod'FMDB',当然也可以自己下载自己手拖到项目里。省点麻烦自己pod进项目。

第一步导入头文件

import "FMDatabase.h"

第一次会报错说未找到这个文件, 没事不用理他

我们需要创建
@property(nonatomic,strong) FMDatabase *db;

我的是直接在controller里创建的方便介绍用法。
NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *fileName=[doc stringByAppendingPathComponent:@"student.sqlite"];
 //2.获得数据库

FMDatabase *db=[FMDatabase databaseWithPath:fileName];


if ([db open]) {

    BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];


    if (result) {

        NSLog(@"创表成功");

    }else

    {

        NSLog(@"创表失败");

    }

}

self.db=db;

这样就创建成功了。
////////////直接添加点击
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

[self insert];

[self query];
[self delete];

}
//插入数据
-(void)insert
{
for (int i = 0; i<10; i++) {
NSString *name = [NSString stringWithFormat:@"jack-%d", arc4random_uniform(100)];
// executeUpdate : 不确定的参数用?来占位
[self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);", name, @(arc4random_uniform(40))];
// [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);" withArgumentsInArray:@[name, @(arc4random_uniform(40))]];

             // executeUpdateWithFormat : 不确定的参数用%@、%d等来占位
            //        [self.db executeUpdateWithFormat:@"INSERT INTO t_student (name, age) VALUES (%@, %d);", name, arc4random_uniform(40)];


     }

}
//删除数据

-(void)delete

{
// [self.db executeUpdate:@"DELETE FROM t_student;"];
[self.db executeUpdate:@"DROP TABLE IF EXISTS t_student;"];
[self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];

}

//查询

  • (void)query
    {
    // 1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM t_student"];

      // 2.遍历结果
    

    while ([resultSet next]) {
    int ID = [resultSet intForColumn:@"id"];
    NSString *name = [resultSet stringForColumn:@"name"];
    int age = [resultSet intForColumn:@"age"];
    NSLog(@"%d %@ %d", ID, name, age);

    }
    }
    这样FMDB简单使用到此结束。 欢迎大神批评指导

相关文章

网友评论

    本文标题:FMDB使用

    本文链接:https://www.haomeiwen.com/subject/iwyosftx.html