| 一、引入工具包 |
引入工具包libsqlite3.dylib,該工具包為C語言工具包。
| 二、代碼操作數(shù)據(jù)庫 |
- (void) _connectDB{ //1>獲取沙盒路徑作為數(shù)據(jù)庫創(chuàng)建時(shí)候的初始化路徑 NSString * path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; path=[path stringByAppendingPathComponent:@"new.sqlite"]; NSLog(@"%@",path); //2>如果存在則打開當(dāng)前鏈接,如果不存在則創(chuàng)建 if(SQLITE_OK==sqlite3_open(path.UTF8String, &sqlite)){ NSLog(@"數(shù)據(jù)庫創(chuàng)建成功!"); }else { NSLog(@"數(shù)據(jù)庫創(chuàng)建失敗!"); } }
/** * 創(chuàng)建表 */- (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:@"創(chuàng)建表操作"]; }/** * 插入數(shù)據(jù)操作 * * @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:@"插入操作"]; }/** * 執(zhí)行數(shù)據(jù)庫操作 * * @param sql 要執(zhí)行的sql * @param tip 要執(zhí)行的操作標(biāo)題 */- (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); }}
/** * 讀取數(shù)據(jù) */- (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> 循環(huán)結(jié)果集取數(shù)據(jù) while(sqlite3_step(stmt)==SQLITE_ROW){ //4>注意:取出來數(shù)據(jù)可以封裝到集合中備用 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); } }}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注