标签:
使用fmdb 做本地数据的存储非常方便,
1. github 上搜索fmdb 下载压缩包 导入到工程中 (如果你的mac 有cocoapod 也可以直接通过cocoapod 添加)
2. 以下代码是通过fmdb 多数据库的各种操作,其中有几点需要注意:(1). 程序中 Ceasar 是表名 (2). 修改数据库数据 提前准备字符串时 值 要用单引号括起来 否则会出错 : NSString *temp = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ‘%@‘ WHERE %@ = ‘%@‘",@"Ceasar",@"Name",@"hao",@"Age",[NSNumber numberWithInt:100]];
NSString *path = @"/Users/shijieli/Desktop/test.sqlite";
FMDatabase *db = [FMDatabase databaseWithPath:path];
if ([db open]) {//创建表
BOOL res = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS Ceasar (Name text, Age integer, Photo blob)"];
if (!res) {
NSLog(@"error when creating db table");
} else {
NSLog(@"success to creating db table");
}
[db close];
}
if ([db open]) {//添加数据
BOOL res = [db executeUpdate:@"INSERT INTO Ceasar (Name, Age, Photo) VALUES (?, ?, ?)",@"Gaius",[NSNumber numberWithInteger:100],[NSData dataWithContentsOfFile:@"/Users/shijieli/Desktop/testPicture.jpg"]];
if (res) {
NSLog(@"success to insert db table");
} else {
NSLog(@"error when insert db table");
}
[db close];
}
if ([db open]) {//查询
FMResultSet * rs = [db executeQuery:@"SELECT * FROM Ceasar"];
while ([rs next]) {
NSString * name = [rs stringForColumn:@"Name"];
int age = [rs intForColumn:@"Age"];
NSData *photo = [rs dataForColumn:@"Photo"];
NSLog(@" name = %@, age = %d", name, age);
BOOL isCreate = [[NSFileManager defaultManager] createFileAtPath:@"/Users/shijieli/Desktop/car.jpg" contents:photo attributes:nil];
if (!isCreate) {
NSLog(@" ****** create failure");
}
}
[db close];
}
// if ([db open]) {//修改数据
// NSString *temp = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ‘%@‘ WHERE %@ = ‘%@‘",@"Ceasar",@"Name",@"hao",@"Age",[NSNumber numberWithInt:100]];
// BOOL res = [db executeUpdate:temp];
// if (!res) {
// NSLog(@"error when update db table");
// } else {
// NSLog(@"success to update db table");
// }
//
// [db close];
//
// }
// if ([db open]) {//清除表
// BOOL res = [db executeUpdate:@"DELETE FROM Ceasar"];
// if (!res) {
// NSLog(@"delete failure");
// }
// }
if ([db open]) {//删除数据
NSString *deleteSql = [NSString stringWithFormat:
@"delete from %@ where %@ = ‘%@‘",
@"Ceasar", @"Name", @"hao"];
BOOL res = [db executeUpdate:deleteSql];
if (!res) {
NSLog(@"error when delete db table");
} else {
NSLog(@"success to delete db table");
}
[db close];
}
}
标签:
原文地址:http://www.cnblogs.com/ceasar/p/5057156.html