IOS開發之資料sqlite使用,ios開發sqlite

來源:互聯網
上載者:User

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);                }        }}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.