IOS sqlite 基礎,iossqlite基礎

來源:互聯網
上載者:User

IOS sqlite 基礎,iossqlite基礎

1,匯入libsqlite3.0.dylib庫

檔案中:#import"sqlite3.h"


2,建立資料庫

#define kDocDir [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

#define dbPath [kDocDir stringByAppendingPathComponent:@"test.db"]


sqlite3 *db;

if (sqlite3_open([dbPath UTF8String], &db) !=SQLITE_OK) {

    sqlite3_close(db);

    NSAssert(0,@"資料庫開啟失敗。");

    return;

}


3,建立表table1, 三個不同類型的欄位id是整形,name是字串,image是二進位

char *sqlStr ="CREATE TABLE table1 (id integer, name text, image blob)";

sqlite3_stmt *statement;

if(sqlite3_prepare_v2(db, sqlStr, -1, &statement,nil) !=SQLITE_OK) {

    NSLog(@"Error: failed to prepare statement:create table1");

    return;

}

int success = sqlite3_step(statement);

sqlite3_finalize(statement);

if ( success != SQLITE_DONE) {

    NSLog(@"Error: failed to dehydrate:CREATE TABLEtable1");

    return;

}


4,插入資料,注意問號的個數要和參數匹配

int idvalue;

NSString *namevalue";

NSData *image;


sqlStr = "INSERT INTO table1 VALUES(?,?,?)";

int success = sqlite3_prepare_v2(db, sqlStr, -1, &statement,NULL);

if (success != SQLITE_OK) {

     NSLog(@"Error: failed to insert into table1");

}

sqlite3_bind_int(statement, 1, [idvalue integerValue]);//第二個參數從1開始,與後面查詢資料的時候有區別

sqlite3_bind_text(statement, 2, [namevalue UTF8String], -1,SQLITE_TRANSIENT);

sqlite3_bind_blob(statement, 3, [image bytes], (int)[image length],SQLITE_TRANSIENT);   

   

success = sqlite3_step(statement);

sqlite3_finalize(statement);

        

if (success == SQLITE_ERROR) {

     NSLog(@"Error: failed to insert into the database with message.");

     return;

}


5, 查詢資料

sqlStr = "SELECT * FROM table1";

if (sqlite3_prepare_v2(db, sqlStr, -1, &statement,NULL) !=SQLITE_OK) {

    NSLog(@"Error: failed to prepare statement with message:gettable1.");

    return;

}

//查詢結果集中一條一條的遍曆所有的記錄,這裡的數字對應的是列值。

while (sqlite3_step(statement) ==SQLITE_ROW) {

     int tempint=sqlite3_column_int(statement, 0);//這裡要從0開始,注意與插入的時候序號的區別


    char *temp=(char *)sqlite3_column_text(statement, 1);

    NSString *tempstr=temp?[NSString stringWithUTF8String:temp]:@"";


    int length=sqlite3_column_bytes(statement,2);//擷取到二進位的資料的長度

    Byte* bytes=(Byte*)sqlite3_column_blob(statement,2);

    NSData *data=[NSData dataWithBytes:byteslength:length];

}

 

6,關閉資料庫   

sqlite3_close(db);


相關文章

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.