IOS FMDB的简单实用
2016-10-18 本文已影响0人
梦之志
对数据库简单的操作: 增删改查
1、确定存储的路径,并创建文件
NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString * fileName=[doc stringByAppendingPathComponent:@"student1.sqlite"];
- 打开文件,并创建表
db = [FMDatabase databaseWithPath:fileName];
if ([db open]) {
NSString * sqlCreadTable = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@'('%@' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'%@'TEXT,'%@' INTEGER,'%@'TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS];
BOOL res = [db executeUpdate:sqlCreadTable];
if (!res) {
NSLog(@"error when creating db table");
}else{
NSLog(@"success to creating db table");
}
3.增: 往表中添加数据
#pragma mark - 添加数据
+(void)AddDate{
if ([db open]) {
//单个数据插入
NSString * insertSql1 = [NSString stringWithFormat:@"INSERT INTO '%@'('%@','%@','%@')VALUES('%@','%@','%@')",TABLENAME,NAME,AGE,ADDRESS,@"张三",@"14",@"晋安"];
BOOL res = [db executeUpdate:insertSql1];
NSString * insertSql2 = [NSString stringWithFormat:@"INSERT INTO '%@'('%@','%@','%@')VALUES('%@','%@','%@')",TABLENAME,NAME,AGE,ADDRESS,@"李四",@"19",@"南昌"];
BOOL res2 = [db executeUpdate:insertSql2];
if (!res && !res2) {
NSLog(@"error when insrt db table");
}else{
NSLog(@"success to insert db table");
}
[db close];
}
}
4.改: 修改数据库中的数据
#pragma mark - 修改数据
+(void)ChageDate{
if ([db open]) {
NSString * updateSql = [NSString stringWithFormat:@"update '%@' set '%@' = '%@' where '%@' = '%@'",TABLENAME,AGE,@"15",AGE,@"13"];
BOOL res = [db executeUpdate:updateSql];
if (!res) {
NSLog(@"error when update db table");
} else {
NSLog(@"success to update db table");
}
[db close];
}
}
5.查: 查询数据
#pragma mark - 查询数据
+(void)SearchDate{
if ([db open]) {
NSString * sql = [NSString stringWithFormat:@"select * from %@",TABLENAME];
FMResultSet * rs = [db executeQuery:sql];
while ([rs next]) {
int Id = [rs intForColumn:ID];
NSString * name = [rs stringForColumn:NAME];
NSString * age = [rs stringForColumn:AGE];
NSString * address = [rs stringForColumn:ADDRESS];
NSLog(@"id = %d, name = %@,age = %@,address = %@",Id,name,age,address);
}
[db close];
}
}
- 删: 删除数据
#pragma mark - 删除数据
+(void)DeleteDate{
if ([db open]) {
NSString * deletesql = [NSString stringWithFormat:@"delete from %@ where %@ = '%@'",TABLENAME,NAME,@"张三"];
BOOL res = [db executeUpdate:deletesql];
if (!res) {
NSLog(@"error when delete db table");
}else {
NSLog(@"success to delete db table");
}
[db close];
}
}