iOS中sqlite的詳細用法_IOS

來源:互聯網
上載者:User

本文執行個體為大家分享了ios中sqlite的具體操作方法,供大家參考,具體內容如下

#import <sqlite3.h>@interface ViewController (){ sqlite3 *_sqldb;}@end@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self OpenDb]; [self createTable]; [self insertData]; [self FindData];}//開啟資料庫-(void)OpenDb{  NSArray *arrs= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //建立資料庫,如果資料庫存在就直接開啟,不存在就建立開啟 NSString *path=[arrs lastObject] ; NSString *documentpath= [path stringByAppendingPathComponent:@"sql.db"]; int reslut= sqlite3_open([documentpath UTF8String], &_sqldb); if(reslut==SQLITE_OK){ NSLog(@"資料庫已被開啟"); } }//通過資料庫執行個體建立表-(void)createTable{ //不帶參數的sql語句 const char* sql="create table if not exists t_person (id integer primary key autoincrement,name text,age integer);"; char *error; //sqlite3_exec可以執行一切不帶參數的SQL語句。如果是帶參數最好不用,防止SQL注入漏洞攻擊 int resutl= sqlite3_exec(_sqldb, sql, NULL, NULL, &error); if(resutl==SQLITE_OK){ NSLog(@"建立表成功"); }else{ NSLog(@"建立表失敗--》%s",error);}}//插入資料-(void)insertData{ //帶參數的SQL語句 "?"是帶參數的預留位置 const char * sql="insert into t_person(name,age) values(?,?);"; sqlite3_stmt *stmp; //在執行SQL語句之前檢查SQL語句文法,-1代表字串的長度 int result= sqlite3_prepare_v2(_sqldb, sql, -1, &stmp, NULL); if(result==SQLITE_OK){ NSLog(@"插入SQL語句文法沒有問題"); //綁定參數,插入的參數的下標是從1開始 sqlite3_bind_text(stmp, 1, "gcb", -1, NULL); sqlite3_bind_int(stmp, 2, 12);  //執行參參數的SQL語句,不能有exec int result=sqlite3_step(stmp); //插入進行判斷,要用sqLite_Done來判斷 if(result==SQLITE_DONE){  NSLog(@"插入成功"); } else{  NSLog(@"插入失敗") ; }  } else{ NSLog(@"插入SQL語句有問題"); }}-(void)FindData{ char *sql="select id,name,age from t_person"; //查詢做好用step執行 sqlite3_stmt *stmt; //檢查SQL語句的文法問題 int result= sqlite3_prepare_v2(_sqldb, sql, -1, &stmt, NULL); if(result==SQLITE_OK){ while (sqlite3_step(stmt)==SQLITE_ROW) {  //查詢的列是0開始 插入的列從1開始//  int xh=sqlite3_column_int(stmt, 0);  int xh=sqlite3_column_int(stmt, 0);  char * name=(char *)sqlite3_column_text(stmt, 1);  int age=sqlite3_column_int(stmt, 2);  NSLog(@"xh=%i-->name=%s-->age=%i",xh,name,age);       } } else{ NSLog(@"查詢SQL文法有誤"); }}

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

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