打开
-(void)opensqlite:(NSString *)sqliteName{
if (!sqliteName || sqliteName.length <= 0) {
NSAssert(sqliteName,@"sqliteName is null");
}
if (!db) {
NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
NSString *path = [basePath stringByAppendingPathComponent:sqliteName];
NSLog(@"sqlite 存放位置:%@",path);
//打开数据库,若存在则打开;反之不存在就创建一个数据库再打开
int result = sqlite3_open([path UTF8String],&db);
if (result == sqlITE_OK) {
NSLog(@"数据库打开成功");
return;
} else {
NSLog(@"数据库打开失败");
}
}
}
创建表 & 删除表(表结构)
- (BOOL)createTable{
NSString *sql = @"create table if not exists 'student' ('number' integer primary key autoincrement not null,'name' text,'sex' text,'age' integer,'score' integer default 0);";
char *error = NULL;
int result = sqlite3_exec(db,[sql UTF8String],nil,&error);
return (result == sqlITE_OK);
}
-(void)dropTable{
NSString *sql = @"DROP TABLE if EXISTS student;";
char *error = NULL;
int ret = sqlite3_exec(db,NULL,&error);
if (ret == sqlITE_OK) {
NSLog(@"删除表格成功");
} else {
NSLog(@"删除失败:%s",error);
}
}
表的增删改查
- (void)insertData{
NSString *sql = @"INSERT INTO student (name,sex,age,score) VALUES ('yy','1',28,99);";
char *error = NULL;
int ret = sqlite3_exec(db,NULL,&error);
if (ret == sqlITE_OK) {
NSLog(@"插入成功");
} else {
NSLog(@"插入失败:%s",error);
}
}
- (void)deleteData{
NSString *sql = @"DELETE FROM student WHRER number = 1;";
int ret = sqlite3_exec(db,NULL);
if (ret == sqlITE_OK) {
NSLog(@"删除成功");
} else {
NSLog(@"删除失败");
}
}
- (void) selectData{
NSString *sql = @"SELECT name,score FROM student;";
sqlite3_stmt *stmt;
int ret = sqlite3_prepare_v2(db,-1,&stmt,NULL);
if (ret == sqlITE_OK) {
// 查询成功 遍历结果集
while (sqlite3_step(stmt) == sqlITE_ROW) {
const unsigned char *name = sqlite3_column_text(stmt,0);
NSInteger score = sqlite3_column_int(stmt,1);
NSLog(@"%@ 分数 %ld",[NSString stringWithUTF8String:(const char *)name],(long)score);
}
} else {
NSLog(@"查询失败");
}
}
解决打印乱码问题
Sending 'const unsigned char *' to parameter of type 'const char * _Nonnull' converts between pointer
强制转化
const unsigned char *name = sqlite3_column_text(stmt,0); NSInteger score = sqlite3_column_int(stmt,1); NSLog(@"%@ 分数 %ld",[NSString stringWithUTF8String:(const char *)name],(long)score);