#import "TableManager.h"
@interface TableManager ()
@property (nonatomic, copy)NSString *sqlitePath;
@end
@implementation TableManager
+ (TableManager *)defaultManager{
static TableManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[TableManager alloc] init];
});
return manager;
}
- (void)creatTable{
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user"];
NSLog(@"%@",path);
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL tag = [fileManager fileExistsAtPath:path isDirectory:NULL];
if (!tag) {
[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL];
}
NSString *tablePath = [path stringByAppendingPathComponent:@"app.sqlite"];
self.sqlitePath = tablePath;
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:tablePath];
[queue inDatabase:^(FMDatabase *db) {
BOOL result1 = [db executeUpdate:@"create table if not exists singer (name text,age integer)"];
if (result1) {
NSLog(@"创表成功1");
} else {
NSLog(@"创表失败1");
}
}];
}
/*
* 增
*/
- (void)add{
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:self.sqlitePath];
[queue inDatabase:^(FMDatabase *db) {
for (int i = 0; i < 100; i++) {
NSString *name = [NSString stringWithFormat:@"name%d",i];
int age = arc4random() % 50 + 20;
BOOL tag = [db executeUpdate:@"insert into singer (name, age) values (?,?)",name,[NSNumber numberWithInt:age]];
if (tag) {
NSLog(@"插入成功");
}
}
}];
}
/*
* 删
*/
- (void)remove{
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:self.sqlitePath];
[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"delete from singer where age < 50;"];
}];
}
/*
* 查
*/
- (void)query{
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:self.sqlitePath];
[queue inDatabase:^(FMDatabase *db) {
FMResultSet * set = [db executeQuery:@"select * from singer order by age desc"];
while (set.next) {
NSLog(@"%@--%d",[set stringForColumn:@"name"],[set intForColumn:@"age"]);
}
}];
}
/*
* 改
*/
- (void)change{
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:self.sqlitePath];
[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"UPDATE singer set age = ? where name = ?",[NSNumber numberWithInt:30],@"name3"];
}];
}
/*
* 添加字段
*/
- (void)addColom:(NSString *)str{
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:self.sqlitePath];
[queue inDatabase:^(FMDatabase *db) {
BOOL tag = [db columnExists:str inTableWithName:@"singer"];
if (tag) {
NSLog(@"存在");
} else {
NSString *sql = [NSString stringWithFormat:@"alter table %@ add column %@",@"singer",str];
BOOL s = [db executeUpdate:sql];
if (s) {
NSLog(@"成功");
}
}
}];
}
@end