標籤:
#import "ViewController.h"#import <sqlite3.h>#import "Person.h"@interface ViewController (){ sqlite3 *_db;}@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/person.db"]; NSLog(@"%@",path); if(SQLITE_OK!=sqlite3_open(path.UTF8String, &_db))//開啟資料庫 不存在則建立 { NSLog(@"開啟或建立資料庫失敗!"); return; } char *error; if(SQLITE_OK!=sqlite3_exec(_db, "create table if not exists ‘t_person‘ (name text,age integer,sex text)", nil, nil, &error)) { NSLog(@"建立表失敗"); return; } //添加資料 修改刪除同理// for (int i=1; i<=50; i++) {// const char *c=[[NSString stringWithFormat:@"insert into t_person values(‘%@‘,%d,‘%@‘)",[NSString stringWithFormat:@"li%d",i],i,i%[email protected]"男":@"女"] UTF8String];// if(SQLITE_OK!=sqlite3_exec(_db, c, nil, nil, &error))// {// NSLog(@"添加資料失敗! error:%s",error);// return;// }// } //查詢 sqlite3_stmt *stmt; if(SQLITE_OK ==sqlite3_prepare(_db, [@"select * from t_person" UTF8String], -1/*要查詢的位元組數 -1表示無限制*/, &stmt, nil/*如果限制位元組 該參數返回未被查詢的資料)) { while(SQLITE_ROW == sqlite3_step(stmt)) { Person *p=[[Person alloc]init]; p.name=[NSString stringWithUTF8String:(const char*)sqlite3_column_text(stmt, 0)]; p.age=sqlite3_column_int(stmt, 1); p.sex=[NSString stringWithUTF8String:(const char*) sqlite3_column_text(stmt, 2)]; NSLog(@"%@--%d--%@",p.name,p.age,p.sex); } }}@end
[IOS:OC]Sqlite建庫建表增刪改查簡單一實例