(三方库 sqlite3) sqlite 语法见 Sqlite.rtf
(导入libsqlite3.bylib )
//找到应用程序的沙箱目录
NSString * path = NSHomeDirectory();
//指定沙箱下数据库文件的路径
path = [path stringByAppendingPathComponent:@"Documents/hello.db"];
// 创建数据库对象
self.db = [FMDatabase databaseWithPath:path];
if ([self.db open]) {
[self createTable];
}else{
NSLog(@"创建或打开数据库失败");
}
// 创建二维表
-(void) createTable{
//如果表存在就什么都不做 (if not exists)
NSString * sql = @"create table if not exists tb_student(stuid integer primary key,stuname varchar(20) not null,stubirth date,stuaddress varchar(50));";
if ([self.db executeUpdate:sql]) {
// [self insertData];
}else{
NSLog(@"创建表失败");
}
}
/*插入数据/ (对方法的注释 是有方法时会有提示)
-(void) insertData{
static NSArray * lastNames = nil;
static NSArray * firstNames = nil;
static NSArray * address = nil;
lastNames = @[@"趙",@"钱",@"孙",@"李",@"上官",@"东方"];
firstNames = @[@"莫愁",@"飘雪",@"霸",@"千锋",@"浩南",@"大神",@"苟且"];
address = @[@"四川成都",@"北京海淀",@"重庆渝北",@"上海浦东"];
NSString * sql = @"insert into tb_student (stuname,stuaddress,stubirth) values (?,?,'1990-1-1')";
int lIndex = arc4random() % lastNames.count;
int fIndex = arc4random() % firstNames.count;
int aIndex = arc4random() % address.count;
NSString * fullName = [NSString stringWithFormat:@"%@%@",lastNames[lIndex],firstNames[fIndex]];
if ([self.db executeUpdate:sql,fullName,address[aIndex]]) {
// [self showData:self.db];
}else{
NSLog(@"插入失败");
}
}
/*查询数据/
-(void) showData{
NSString * sql = @"select * from tb_student;";
//结果集 游标
FMResultSet * rs = [self.db executeQuery:sql];
//[rs next] 取到一行 就返回
while ([rs next]) {
printf("学号:%d ",[rs intForColumn:@"stuid"]);
printf("姓名:%s ",[[rs stringForColumn:@"stuname"] cStringUsingEncoding:NSUTF8StringEncoding]);
printf("生日:%s ",[[rs stringForColumn:@"stubirth"] cStringUsingEncoding:NSUTF8StringEncoding]);
printf("家庭住址:%s\n",[[rs stringForColumn:@"stuaddress"] cStringUsingEncoding:NSUTF8StringEncoding]);
}
}