本文實例為大家分享了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語法有誤");
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助。