-
導入libsqlite3.0.tbd庫
導入sql庫
-
實現(xiàn)數(shù)據(jù)庫的增刪查改
#import "ViewController.h"
#import <sqlite3.h>
@interface ViewController ()
//更新
- (IBAction)updateBtn;
//查詢
- (IBAction)selectBtn;
//添加
- (IBAction)insterBtn;
//刪除
- (IBAction)deleteBtn;
//db就是數(shù)據(jù)庫的象征弃甥,增,刪,改她渴,查就是操作db實例
@property(nonatomic,assign)sqlite3 *db;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 數(shù)據(jù)庫文件一般存儲在沙盒當中倚评,所以首先獲取數(shù)據(jù)庫文件路徑
NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSLog(@"%@",document);
//創(chuàng)建數(shù)據(jù)庫文件
NSString *fileName = [document stringByAppendingPathComponent:@"Student.sqlite"];
//打開數(shù)據(jù)庫
//第一個參數(shù):const char *filename
//C語言字符串(需要將OC轉(zhuǎn)為C語言的字符串)
//第二個參數(shù):sqlite3 **ppDb 數(shù)據(jù)庫實例
const char *cfileName = fileName.UTF8String;
int result = sqlite3_open(cfileName, &_db);
if (result == SQLITE_OK) {//SQLITE_OK 數(shù)據(jù)庫打開成功
NSLog(@"數(shù)據(jù)庫打開成功");
//數(shù)據(jù)庫只有打開成功才可創(chuàng)建表
//建表
//1.代表的是數(shù)據(jù)庫
//2.sql語句 if not exists:如果不存在就創(chuàng)建忆畅,反之...
//primary key autoincrement 主鍵自增
//
const char *sql = "create table if not exists t_student (id integer primary key autoincrement,name text not null,age integer not null);";
//3.指向函數(shù)的指針
//4.nil 第一個參數(shù)回調(diào)
//5.錯誤信息
result = sqlite3_exec(self.db, sql, NULL, NULL, NULL);
if (result == SQLITE_OK) {
NSLog(@"建表成功");
} else {
NSLog(@"建表失敗---%s---%d",__FILE__,__LINE__);
}
}else{
NSLog(@"數(shù)據(jù)庫打開失敗");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
//更新
- (IBAction)updateBtn {
}
//查詢
- (IBAction)selectBtn {
//第一個參數(shù):數(shù)據(jù)庫實例
//第二個參數(shù):sql語句
const char *sql = "select id, name, age from t_student where age = 40";
//第三個參數(shù):-1 -> 系統(tǒng)自動計算sql語句長度
//第四個參數(shù):伴隨指針 -> 取數(shù)據(jù)
sqlite3_stmt *stmt = NULL;
//第五個參數(shù):NULL
if (sqlite3_prepare(self.db, sql, -1, &stmt, NULL) == SQLITE_OK) {
NSLog(@"查詢語句沒有問題");
//取數(shù)據(jù)
//sqlite3_step每調(diào)用一次setp就從&stmt中取一次數(shù)據(jù)
while (sqlite3_step(stmt) == SQLITE_ROW) {//SQLITE_ROW 行數(shù)
//取出數(shù)據(jù)
//取出第一列字段的值(int 類型)
int ID = sqlite3_column_int(stmt, 0);
//取出第二列字段的值(text 類型)
const unsigned char *name = sqlite3_column_text(stmt, 1);
//取出第三列字段的值 (int 類型)
int age = sqlite3_column_int(stmt, 2);
NSLog(@"%d %s %d",ID,name,age);
}
} else {
NSLog(@"select error挎扰!");
}
}
//插入
- (IBAction)insterBtn {
char *errorMsg = NULL;
for (int i=0; i<20; i++) {
//
NSString *name = [NSString stringWithFormat:@"Xm-%d",arc4random_uniform(100)];
int age = arc4random_uniform(20) + 30;
//sql語句
NSString *sql = [NSString stringWithFormat:@"insert into t_student(name,age) values('%@','%d')",name,age];
sqlite3_exec(self.db, sql.UTF8String, NULL, NULL, &errorMsg);
}
if (errorMsg) {
NSLog(@"數(shù)據(jù)有誤 %s",errorMsg);
}else{
NSLog(@"插入成功");
}
}
//刪除
- (IBAction)deleteBtn {
}
@end