1 數(shù)據(jù)庫(kù)打開
+ (instancetype)shareDataBaseHandler{
//單例創(chuàng)建
static HPZDataHandle *hdHandler = nil;
if(hdHandler == nil){
hdHandler = [[HPZDataHandle alloc] init];
}
return hdHandler;
}
創(chuàng)建一個(gè)sqlite3 對(duì)象
sqlite3 *hd;
if (hd) {
NSLog(@"數(shù)據(jù)庫(kù)已打開");
return;
}
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"huliji.sqlite"];
NSLog(@"%@",path);
int result = sqlite3_open(path.UTF8String, &hd);
if (result == SQLITE_OK) {
NSLog(@"數(shù)據(jù)庫(kù)打開成功");
}else{
NSLog(@"數(shù)據(jù)庫(kù)打開失敗,錯(cuò)誤碼:%d",result);
}```
#2 基本語(yǔ)句
1.創(chuàng)建表
```sqlite
"CREATE TABLE IF NOT EXISTS Hunliji (Cate INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT,image TEXT)"
2.插入數(shù)據(jù)
NSString *sql = [NSString stringWithFormat:@"INSERT INTO Hunliji(title,image) VALUES('%@','%@')",model.title,model.cover_path];
3.更新數(shù)據(jù)
NSString *sql = [NSString stringWithFormat:@"UPDATE Hunliji SET title = '%@',image = '%@' WHERE title = '%@'",model.title,model.cover_path,title];
4.刪除數(shù)據(jù)
NSString *sql = [NSString stringWithFormat:@"UPDATE Hunliji SET title = '%@',image = '%@' WHERE title = '%@'",model.title,model.cover_path,title];
5.查詢表
NSMutableArray *arr = [NSMutableArray array];
//查找sql語(yǔ)句
NSString *sql = [NSString stringWithFormat:@"select *from Hunliji"];
//創(chuàng)建一個(gè) 準(zhǔn)備好的語(yǔ)句對(duì)象
sqlite3_stmt *stmt = nil;
//為準(zhǔn)備好的語(yǔ)句對(duì)象賦值(SQL語(yǔ)句內(nèi)容)
int result = sqlite3_prepare_v2(hd, sql.UTF8String, -1, &stmt, nil);
if (result == SQLITE_OK) {
NSLog(@"開始查詢");
while (sqlite3_step(stmt) == SQLITE_ROW) {
//查詢條件匹配,使用sqlite3_column函數(shù)簇 將需要的列值取出來(lái)
const unsigned char *title = sqlite3_column_text(stmt, 1);
const unsigned char *image = sqlite3_column_text(stmt, 2);
//model賦值
HPZModelOfEntity *model = [[HPZModelOfEntity alloc] init];
model.title = [NSString stringWithUTF8String:(const char*) title];
model.cover_path = [NSString stringWithUTF8String:(const char*) image];
[arr addObject:model];
結(jié)果返回一個(gè)存放查詢到數(shù)據(jù)的數(shù)組
6.刪除表
DROP TABLE Hunliji