IOS開發之數據SQLite使用
一、引入工具包 | </tr> </tbody> </table>
二、代碼操作數據庫 |
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); } } }
本文由用戶 ybny 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!