iOS 数据库增删改查创建

我这使用FMDB数据库框架

1.通过路径创建数据库

    self.db = [FMDatabase databaseWithPath:sqlFilePath];

2.打开数据库

    if ([self.db open]) {
        NSLog(@"打开成功");
        BOOL success = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER DEFAULT 1)"];
        
        if (success) {
            NSLog(@"创建表成功");
        } else {
            NSLog(@"创建表失败");
        }
        
    } else {
        NSLog(@"打开失败");
    }
#pragma mark 增加数据

static NSInteger age = 10;
    for (int i = 0; i < 20; i++) {
        age++;
        BOOL success = [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);", @"jack", @(age)];
        [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES(?,?);",@"jack",@(age)];
        if (success) {
            NSLog(@"插入成功");
        } else {
            NSLog(@"插入失败");
        }
    }

pragma mark 删除数据

BOOL success = [self.db executeUpdate:@"DELETE FROM t_student WHERE age > 20 AND age < 25;"];

pragma mark 修改数据

BOOL success = [self.db executeUpdate:@"UPDATE t_student SET name = 'liwx' WHERE age > 12 AND age < 15;"];

pragma mark 查询数据

FMResultSet *result = [self.db executeQuery:@"SELECT id, name, age FROM t_student WHERE age > 25;"];
    while ([result next]) {
        int ID = [result intForColumnIndex:0];
        NSString *name = [result stringForColumnIndex:1];
        int age = [result intForColumn:@"age"];
        
        NSLog(@"ID: %zd, name: %@, age: %zd", ID, name, age);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容