日期:2014-05-16 浏览次数:20550 次
#define kFileName @"archive" #define kDataKey @"Data" #define kSqliteFileName @"data.db3" #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property(nonatomic,retain)IBOutlet UITextField *name; @property(nonatomic,retain)IBOutlet UITextField *gender; @property(nonatomic,retain)IBOutlet UITextField *age; @property(nonatomic,retain)IBOutlet UITextField *education; -(NSString *)dataFilePath; -(void)applicationWillResignActive:(NSNotification *)nofication; @end
#import "ViewController.h" #import "Person.h" #import <sqlite3.h> @implementation ViewController @synthesize name,gender,age,education; -(NSString *)dataFilePath{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); NSString *documentsDirectory = [paths objectAtIndex:0]; //return [documentsDirectory stringByAppendingPathComponent:kFileName]; return [documentsDirectory stringByAppendingPathComponent:kSqliteFileName]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { // Do any additional setup after loading the view, typically from a nib. NSString *filePath = [self dataFilePath]; NSLog(@"filePath=%@",filePath); if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ //属性列表 /* NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath]; name.text = [array objectAtIndex:0]; gender.text = [array objectAtIndex:1]; age.text = [array objectAtIndex:2]; education.text = [array objectAtIndex:3]; [array release];*/ //归档 /* NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[self dataFilePath]]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data]; Person *person = [unarchiver decodeObjectForKey:kDataKey]; [unarchiver finishDecoding]; name.text = person.name; gender.text = person.gender; age.text = person.age; education.text = person.education; [unarchiver release]; [data release];*/ //sqlite3 sqlite3 *database; //打开数据库 if(sqlite3_open([filePath UTF8String], &database)!=SQLITE_OK){//备注1 //数据库打开失败,关闭数据库 sqlite3_close(database); NSAssert(0,@"打开数据库失败"); } char* errorMsg; NSString *createSQL = @"CREATE TABLE IF NOT EXISTS PERSON (name TEXT PRIMARY KEY,gender TEXT,age TEXT,education TEXT);"; //创建表 if(sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg)!=SQLITE_OK){//备注2 //创建表失败,关闭数据库 sqlite3_close(database); NSAssert1(0, @"创建表失败:%s", errorMsg); } //查询表 NSString *querySQL = @"SELECT name,gender,age,education FROM PERSON ORDER BY name"; //执行查询,遍历查询结果 sqlite3_stmt *statment; if(sqlite3_prepare_v2(database, [querySQL UTF8String], -1, &