标签:io ar os sp for on 2014 log bs
//
// ZBMainViewController.m
// FMDBDemo
//
// Created by 张先森 on 14/11/27.
// Copyright (c) 2014年 zhibin. All rights reserved.
//
#import "ZBMainViewController.h"
#import "FMDatabase.h"
@interface ZBMainViewController ()
- (IBAction)Create:(id)sender;
- (IBAction)Insert:(id)sender;
- (IBAction)Edit:(id)sender;
- (IBAction)Del:(id)sender;
- (IBAction)Select:(id)sender;
@end
FMDatabase *db;
NSString *TABLENAME=@"zbtest";
@implementation ZBMainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self InitDataBase];
}
-(void)InitDataBase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"MyProject.db"];
db = [FMDatabase databaseWithPath:dbPath];
}
- (IBAction)Create:(id)sender {
if ([db open]) {
NSString *createtable= [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS ‘%@‘ (‘%@‘ INTEGER PRIMARY KEY AUTOINCREMENT, ‘%@‘ TEXT, ‘%@‘ INTEGER, ‘%@‘ TEXT)",TABLENAME,@"ID",@"NAME",@"AGE",@"ADDRESS"];
BOOL result=[db executeUpdate:createtable];
if (!result) {
NSLog(@"error when creating db table");
} else {
NSLog(@"success to creating db table");
}
[db close];
}
}
- (IBAction)Insert:(id)sender {
if ([db open]) {
NSString *insertdata=[NSString stringWithFormat:
@"INSERT INTO ‘%@‘ (‘%@‘, ‘%@‘, ‘%@‘) VALUES (‘%@‘, ‘%@‘, ‘%@‘)",
TABLENAME, @"NAME", @"AGE", @"ADDRESS", @"张三", @"13", @"济南"];
BOOL result=[db executeUpdate:insertdata];
if (!result) {
NSLog(@"error when insert db table");
} else {
NSLog(@"success to insert db table");
}
[db close];
}
}
- (IBAction)Edit:(id)sender {
if ([db open]) {
BOOL res = [db executeUpdate:@"UPDATE zbtest SET AGE=? WHERE AGE=?",@"15",@"13"];
if (!res) {
NSLog(@"error when update db table");
} else {
NSLog(@"success to update db table");
}
[db close];
}
}
- (IBAction)Del:(id)sender {
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];
}
}
- (IBAction)Select:(id)sender {
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];
}
}
@end
标签:io ar os sp for on 2014 log bs
原文地址:http://www.cnblogs.com/zhibin/p/4127252.html