1 数据库打开
+ (instancetype)shareDataBaseHandler{
//单例创建
static HPZDataHandle *hdHandler = nil;
if(hdHandler == nil){
hdHandler = [[HPZDataHandle alloc] init];
}
return hdHandler;
}
创建一个sqlite3 对象
sqlite3 *hd;
if (hd) {
NSLog(@"数据库已打开");
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(@"数据库打开成功");
}else{
NSLog(@"数据库打开失败,错误码:%d",result);
}```
#2 基本语句
1.创建表
```sqlite
"CREATE TABLE IF NOT EXISTS Hunliji (Cate INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT,image TEXT)"
2.插入数据
NSString *sql = [NSString stringWithFormat:@"INSERT INTO Hunliji(title,image) VALUES('%@','%@')",model.title,model.cover_path];
3.更新数据
NSString *sql = [NSString stringWithFormat:@"UPDATE Hunliji SET title = '%@',image = '%@' WHERE title = '%@'",model.title,model.cover_path,title];
4.删除数据
NSString *sql = [NSString stringWithFormat:@"UPDATE Hunliji SET title = '%@',image = '%@' WHERE title = '%@'",model.title,model.cover_path,title];
5.查询表
NSMutableArray *arr = [NSMutableArray array];
//查找sql语句
NSString *sql = [NSString stringWithFormat:@"select *from Hunliji"];
//创建一个 准备好的语句对象
sqlite3_stmt *stmt = nil;
//为准备好的语句对象赋值(SQL语句内容)
int result = sqlite3_prepare_v2(hd, sql.UTF8String, -1, &stmt, nil);
if (result == SQLITE_OK) {
NSLog(@"开始查询");
while (sqlite3_step(stmt) == SQLITE_ROW) {
//查询条件匹配,使用sqlite3_column函数簇 将需要的列值取出来
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];
结果返回一个存放查询到数据的数组
6.删除表
DROP TABLE Hunliji