时间:2021-07-01 10:21:17 帮助过:3人阅读
//<0>FMDB库的配置 //<1>创建打开数据库 [self createAndOpenDatabase]; -(void)createAndOpenDatabase { // sandbox NSString *path = [NSString stringWithFormat:@"%@/Documents/stu.rdb",NSHomeDirectory()];//沙盒 NSLog(@"path = %@",path); //初始化数据 _database = [[FMDatabase alloc] initWithPath:path]; //open一定需要执行, 如果没有文件创建文件 if(!_database.open) { NSLog(@"打开失败"); return; } NSLog(@"打开成功"); } //<2>创建表 [self testCreateTabel]; -(void)testCreateTabel { NSString *sql = @"create table if not exists stuInfo(sid varchar(12),username varchar(12),password varchar(12),age integer)"; //注意: select查询语句使用executeQuery // 其他语句使用executeUpdate BOOL b = [_database executeUpdate:sql]; b?NSLog(@"创建成功"):NSLog(@"创建失败"); } //<3>插入数据 //[self testInsertData]; -(void)testInsertData { NSString *sid = @"13121113"; NSString *username = @"zhangsan"; NSString *password = @"111"; int age = 23; NSString *sql = @"insert into stuInfo(sid,username,password,age) values(?,?,?,?)"; //注意: 任何数据转化为字符串传入 BOOL b = [_database executeUpdate:sql,sid,username,password,@(age).stringValue]; b?NSLog(@"插入成功"):NSLog(@"插入失败"); } //<4>查询数据 //[self testQueryData]; -(void)testQueryData { NSString *sql = @"select * from stuInfo"; FMResultSet *result = [_database executeQuery:sql]; //每次使用next获取一行, 没有返回nil while ([result next]) { //每次获取一条记录的各个字段 NSLog(@"%@ %@ %@ %d", [result stringForColumn:@"sid"], [result stringForColumn:@"username"], [result stringForColumn:@"password"], [result intForColumn:@"age"]); } } //<5>更新数据 //[self updateData]; -(void)updateData { NSString *username = @"zhangsan"; NSString *newPassword = @"666"; NSString *sql = @"update stuInfo set password=? where username=?"; //注意: 任何数据转化为字符串传入 BOOL b = [_database executeUpdate:sql,newPassword,username]; b?NSLog(@"更新成功"):NSLog(@"更新失败"); }; //<6>删除数据 -(void)deleteData { NSString *username = @"zhangsan"; NSString *sql = @"delete from stuInfo where username=?"; //注意: 任何数据转化为字符串传入 BOOL b = [_database executeUpdate:sql,username]; b?NSLog(@"删除成功"):NSLog(@"删除失败"); }View Code
FMDatabase 使用
标签: