欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS中sqlite的詳細(xì)用法

 更新時(shí)間:2016年05月05日 09:42:35   作者:甘超波  
在iOS中,也同樣支持sqlite。目前有很多第三方庫(kù),封裝了sqlite操作,比如swift語言寫的SQLite.swift,對(duì)sqlite感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了ios中sqlite的具體操作方法,供大家參考,具體內(nèi)容如下

#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];
}


//打開數(shù)據(jù)庫(kù)

-(void)OpenDb{
 
 NSArray *arrs= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 //創(chuàng)建數(shù)據(jù)庫(kù),如果數(shù)據(jù)庫(kù)存在就直接打開,不存在就創(chuàng)建打開
 NSString *path=[arrs lastObject] ;
 NSString *documentpath= [path stringByAppendingPathComponent:@"sql.db"];
 int reslut= sqlite3_open([documentpath UTF8String], &_sqldb);
 if(reslut==SQLITE_OK){
 NSLog(@"數(shù)據(jù)庫(kù)已被打開");
 }
 
}
//通過數(shù)據(jù)庫(kù)實(shí)例創(chuàng)建表
-(void)createTable{
 //不帶參數(shù)的sql語句
 const char* sql="create table if not exists t_person (id integer primary key autoincrement,name text,age integer);";
 char *error;
 //sqlite3_exec可以執(zhí)行一切不帶參數(shù)的SQL語句。如果是帶參數(shù)最好不用,防止SQL注入漏洞攻擊
 int resutl= sqlite3_exec(_sqldb, sql, NULL, NULL, &error);
 if(resutl==SQLITE_OK){
 NSLog(@"創(chuàng)建表成功");
 }
else{
 NSLog(@"創(chuàng)建表失敗--》%s",error);
}
}

//插入數(shù)據(jù)
-(void)insertData{
 //帶參數(shù)的SQL語句 "?"是帶參數(shù)的占位符
 const char * sql="insert into t_person(name,age) values(?,?);";
 sqlite3_stmt *stmp;
 //在執(zhí)行SQL語句之前檢查SQL語句語法,-1代表字符串的長(zhǎng)度
 int result= sqlite3_prepare_v2(_sqldb, sql, -1, &stmp, NULL);
 if(result==SQLITE_OK){
 NSLog(@"插入SQL語句語法沒有問題");
 //綁定參數(shù),插入的參數(shù)的下標(biāo)是從1開始
 sqlite3_bind_text(stmp, 1, "gcb", -1, NULL);
 sqlite3_bind_int(stmp, 2, 12);
 
 //執(zhí)行參參數(shù)的SQL語句,不能有exec
 int result=sqlite3_step(stmp);
 //插入進(jìn)行判斷,要用sqLite_Done來判斷
 if(result==SQLITE_DONE){
  NSLog(@"插入成功");
 }
 else{
  NSLog(@"插入失敗") ;
 }
 
 }
 else{
 NSLog(@"插入SQL語句有問題");
 }
}

-(void)FindData{
 char *sql="select id,name,age from t_person";
 //查詢做好用step執(zhí)行
 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語法有誤");
 }

}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論