数据库
手动创建数据库和表
#import "ViewController.h"
//先拖入FMDB文件,并且引入.h头文件
#import "FMDatabase.h"
@interface ViewController (){
FMDatabase *db;
NSMutableArray *a;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//先在Documents文件夹下创建一个my.sqlite文件(数据库文件)路径,用NSString存起来
NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/my.sqlite"];
//通过路径,建立一个数据库
db = [[FMDatabase alloc]initWithPath:path];
//将数据库的sql语句(数据库中的字段(列标题)),存成一个NSString,tableone是数据库上面的分类
NSString *sql = @"create table if not exists tableone(id text primary key, name text, age text) ";
//如果数据库打开
if ([db open]) {
//创建一个BOOL类型,来判断数据库sql(语句(列标题))创建的方法
BOOL yesOrNo = [db executeUpdate:sql];
//如果yesOrNo
if (yesOrNo) {
//则打印创建成功
NSLog(@"数据库创建成功");
//增加单条数据,tableone是数据库上面的分类
BOOL insetOk = [db executeUpdate:@"insert into tableone(id,name,age) values(?,?,?)",@"1",@"xiaoming",@"23"];
//添加成功,则打印1,不成功打印0
NSLog(@"%d", insetOk);
//添加多条数据
[db executeUpdate:@"insert into tableone (id,name,age) select '2','xiaohong','24' union all select '3','xiaoqiang','18' union all select '13','xiaoliang','100' "];
//删除一条数据
[db executeUpdate:@"delete from tableone where id = '1'"];
//更新(修改)一条数据
[db executeUpdate:@"update tableone set name = 'chaoren' where id = '2'"];
//查询一条数据
a = [[NSMutableArray alloc]initWithCapacity:10];
//先通过ID
FMResultSet *re = [db executeQuery:@"select * from tableone where id = '2'"];
//再通过数据库里面的(列标题),查询出内容,并添加到数组a
while ([re next]) {
NSString *ids = [re stringForColumn:@"id"];
NSString *names = [re stringForColumn:@"name"];
NSString *ages = [re stringForColumn:@"age"];
[a addObject:ids];
[a addObject:names];
[a addObject:ages];
}
}else{
//反之,则打印创建失败
NSLog(@"数据库创建失败");
}
NSLog(@"%@", a);
}
对于已经存在的数据库的使用
#import "ViewController.h"
//先拖入FMDB文件,并且引入.h头文件
#import "FMDatabase.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//新建一个数据库
FMDatabase *dbb;
dbb = [self dataBase:nil];
if ([dbb open]) {
NSString *que = @"select * from acupoint_cn where id = '1'";
FMResultSet *res = [dbb executeQuery:que];
while ([res next]) {
NSString *nameString = [res stringForColumn:@"dissection"];
NSLog(@"%@", nameString);
}
}
}
-(FMDatabase *)dataBase:(id)sender{
//已经存在的数据库
//先拖入meridianPoint.sqlite文件
//将meridianPoint.sqlite文件的路径存到NSString中
NSString *bundleStringPath = [[NSBundle mainBundle]pathForResource:@"meridianPoint" ofType:@"sqlite"];
NSString *documentsStringPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/mysqlite.sqlite"];
NSFileManager *fileMa = [NSFileManager defaultManager];
NSError *errorNow;
if (![fileMa fileExistsAtPath:documentsStringPath]) {
if (![fileMa copyItemAtPath:bundleStringPath toPath:documentsStringPath error:&errorNow]) {
NSLog(@"%@", errorNow.localizedDescription);
}
}
FMDatabase *db = [FMDatabase databaseWithPath:documentsStringPath];
return db;
}