SQLite的基本封装
/** 获取单例对象 */ + (instancetype)shareManage;
static SQLManager *_instance; + (instancetype)shareManage { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[SQLManager alloc] init]; }); return _instance; }
+ (void)initialize { // 拼接数据库地址 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; NSString *sqlFile = [path stringByAppendingPathComponent:@"student.sqlite"]; // 打开数据 int result = sqlite3_open(sqlFile.UTF8String, &_db);// [self db] // 判断是否打开成功 if (result == SQLITE_OK) { NSLog(@"打开成功"); // 3.1创建表 NSString *sql = @"CREATE TABLE IF NOT EXISTS t_student(id INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT, age INTEGER, score REAL);"; result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, NULL); } }
/** 插入学生数据 */ - (BOOL)insertStudent:(HMStudent *)student;
@property (nonatomic, copy) NSString *name; @property (nonatomic, assign) int age; @property (nonatomic, assign) double score; @property (nonatomic, assign) int ID;
- (BOOL)insertStudent:(HMStudent *)student { NSString *sql = [NSString stringWithFormat: @"INSERT INTO t_student(age, score, name) VALUES (%d, %f, '%@');", student.age, student.score, student.name]; int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, NULL); if (result == SQLITE_OK) { return YES; } return NO; }
Student *stu = [[Student alloc] init]; stu.name = @"lnj"; stu.age = 30; stu.score = 100.0; if ([[SQLManager shareManage]insertStudent:stu]) { NSLog(@"插入成功"); }
- (NSArray *)query;
NSString *sql = @"SELECT * FROM t_student;"; sqlite3_stmt *stemt = NULL; sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stemt, NULL); // 判断有没有查询结果 NSMutableArray *arrM = [NSMutableArray array]; while (sqlite3_step(stemt) == SQLITE_ROW) { // 取出查询到得结果 const unsigned char *name = sqlite3_column_text(stemt, 1); int age = sqlite3_column_int(stemt, 2); double score = sqlite3_column_double(stemt, 3); HMStudent *stu = [[HMStudent alloc] init]; stu.name = [NSString stringWithUTF8String:name]; stu.age = age; stu.score = score; [arrM addObject:stu]; } return arrM;
NSArray *arr = [[SQLManager shareManage] query]; for (Student *stu in arr) { NSLog(@"%@", stu); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。