Ios開發之sqlite,iossqlite

來源:互聯網
上載者:User

Ios開發之sqlite,iossqlite

  Sqlite是ios資料存放區的一個重要手段,今天我們就一塊來看一下,怎樣使用sqlite將資料存放區到沙箱中去。

  第一步:匯入一個架構libsqlite3.0.dylib

  選中TARGETS在General中的Linked Frameworks and Libraries選項中點擊‘+’添加

第二步:代碼部分

    1.找到沙箱中的路徑

NSArray *path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentPath = [path objectAtIndex:0]; NSString *dbPath = [documentPath stringByAppendingPathComponent:@"sqlite.db"];

    2.建立sqlite對象,並執行開啟操作

sqlite3 *db;    //開啟資料庫int res = sqlite3_open(dbPath.UTF8String, &db);

3.建立表

NSString *sql = @"create table if not exists 'student' ('id' integer primary key autoincrement,'studentname' varchar)";int sqlRes = sqlite3_exec(db, sql.UTF8String, NULL, NULL, NULL); if (sqlRes == SQLITE_OK) {     NSLog(@"create table ok"); }

4.向表中插入資料

//增 NSString *sql1 = @"insert into student (studentname) values ('小帳')";int sql1Res = sqlite3_exec(db, sql1.UTF8String, NULL, NULL, NULL);if (sql1Res == SQLITE_OK) {    NSLog(@"insert ok");}

    5.從表中刪除資料

NSString *deletesql  = @"delete from student where id = 3";int deleres = sqlite3_exec(db, deletesql.UTF8String, NULL, NULL, NULL);if (deleres == SQLITE_OK) {     NSLog(@"delete is ok");}

6.修改表中的資料

//修改NSString *updateSql = @"update student set studentname = 'wangling' where id = 4";int updateres = sqlite3_exec(db, updateSql.UTF8String, NULL, NULL, NULL);if (updateres == SQLITE_OK) {      NSLog(@"update is ok");}

        7.查詢資料

  查詢資料和,增刪改都有所不同,我們需要首先建立sqlite_stmt對象,用來存放我們查詢的資料流(二進位),然後使用sqlite3_prepare_v2函數準備,通過sqlite3_bind_添加查詢參數最後擷取資料,最後關閉sqlite_stmt對象。

//查        sqlite3_stmt *stmt;        NSString *selectSql = @"select * from student where id = ?";        if (sqlite3_prepare_v2(db, selectSql.UTF8String, -1, &stmt, nil) == SQLITE_OK) {            sqlite3_bind_int(stmt, 1, 4);            while (sqlite3_step(stmt) == SQLITE_ROW) {                int identity = sqlite3_column_int(stmt, 0);                NSLog(@"%d",identity);                char * name= (char *)sqlite3_column_text(stmt, 1);                NSLog(@"%@",[NSString stringWithUTF8String:name]);            }            if (stmt) {                sqlite3_finalize(stmt);}

8.關閉資料庫sqlite對象

if (db) {        sqlite3_close(db);    }

 

作者:傑瑞教育
出處:http://www.cnblogs.com/jerehedu/ 
著作權聲明:本文著作權歸煙台傑瑞教育科技有限公司和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。
技術諮詢: 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.