IOS開發之資料sqlite使用,ios開發sqlite
引入工具包libsqlite3.dylib,該工具包為C語言工具包。
1、建立並且連結資料庫
- (void) _connectDB{ //1>擷取沙箱路徑作為資料庫建立時候的初始化路徑 NSString * path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; path=[path stringByAppendingPathComponent:@"new.sqlite"]; NSLog(@"%@",path); //2>如果存在則開啟當前連結,如果不存在則建立 if(SQLITE_OK==sqlite3_open(path.UTF8String, &sqlite)){ NSLog(@"資料庫建立成功!"); }else { NSLog(@"資料庫建立失敗!"); } }
2、操作資料庫
/** * 建立表 */- (void) _createTable{ NSString *create=@" create table if not exists t_Person (id integer primary key autoincrement,name text,age integer,tel text)"; [self _execSql:create andTip:@"建立表操作"]; }/** * 插入資料操作 * * @param name 姓名 * @param age 年齡 * @param tel 電話 */- (void) _insertName:(NSString *) name andAge:(int )age andTel:(NSString *) tel{ NSString * insert=[NSString stringWithFormat:@" insert into t_Person(name,age,tel) values('%@',%d,'%@')",name,age,tel]; [self _execSql:insert andTip:@"插入操作"]; }/** * 執行資料庫操作 * * @param sql 要執行的sql * @param tip 要執行的操作標題 */- (void) _execSql:(NSString *) sql andTip:(NSString *) tip{ char * result; if(SQLITE_OK==sqlite3_exec(sqlite, sql.UTF8String, NULL, NULL, &result)){ NSLog(@"%@成功!",tip); }else{ NSLog(@"%@失敗!",tip); }}
3、查詢資料庫
/** * 讀取資料 */- (void)_readData{ //1> 定義sql語句 NSString * sql=@"select id,name,age,tel from t_person "; sqlite3_stmt * stmt=NULL; //2> 檢查文法的正確性 if(SQLITE_OK==sqlite3_prepare_v2(sqlite, sql.UTF8String, -1, &stmt, NULL)){ //3> 迴圈結果集取資料 while(sqlite3_step(stmt)==SQLITE_ROW){ //4>注意:取出來資料可以封裝到集合中備用 int ID=sqlite3_column_int(stmt,0); const unsigned char *name=sqlite3_column_text(stmt, 1); int age=sqlite3_column_int(stmt, 2); const unsigned char *tel=sqlite3_column_text(stmt, 3); NSString * names=[NSString stringWithUTF8String:(const char *)name]; NSString * tels=[NSString stringWithUTF8String:(const char *)tel]; NSLog(@"%d,%@,%d,%@",ID,names,age,tels); } }}