- (void)viewDidLoad {
[super viewDidLoad];[self openSqlite];
[self creatTable];
[self insert];
[self updata];
[self query];
[self closeSqlite];
}
static sqlite3 *db;
-(void)openSqlite{
NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"student.sqlite"]; //数据库文件路径
//如果文件存在,则打开数据库文件,如果不存在则创建,并且打开
int result = sqlite3_open(filename.UTF8String, &db);
//判断是否打开数据库成功
if (result == SQLITE_OK) {
NSLog(@"打开数据库成功");
}else{
NSLog(@"打开失败");
}
}
-(void)closeSqlite{
int result = sqlite3_close(db);
//判断是否打开数据库成功
if (result == SQLITE_OK) {
NSLog(@"关闭数据库成功");
}else{
NSLog(@"关闭失败");
}
}
-(BOOL)creatTable
{
char *sql = "create table if not exists student(id integer primary key autoincrement,name text,age integer,score integer);";
char *errorMesg = NULL;
int result = sqlite3_exec(db, sql, NULL, NULL, &errorMesg);//用于操作数据库
if (result == SQLITE_OK) {
NSLog(@"创建表成功");
return YES;
}else{
NSLog(@"创建表失败,失败原因:%s",errorMesg);
return NO;
}
}
-(BOOL)insert
{
char *sql = "insert into student(name,age,score) values('jack',20,80)";
char *errorMesg = NULL;
int result = sqlite3_exec(db, sql , NULL, NULL, &errorMesg);
if (result == SQLITE_OK) {
NSLog(@"插入数据成功");
return YES;
}else{
NSLog(@"插入数据失败,失败原因:%s",errorMesg);
return NO;
}
}
-(BOOL)updata
{
char *sql = "update student set age = 12 where name = 'jack'";
char *errorMesg = NULL;
int result = sqlite3_exec(db, sql , NULL, NULL, &errorMesg);
if (result == SQLITE_OK) {
NSLog(@"更新成功");
return YES;
}else {
NSLog(@"更新数据失败,失败原因:%s",errorMesg);
return NO;
}
}
- (void)delete{
char *sql = "delete from student where name = 'xiaoming'";
char *error = NULL;
int result = sqlite3_exec(db, sql , NULL, NULL, &error);
if(result == SQLITE_OK){
NSLog(@"删除成功");
}else {
NSLog(@"删除失败");
}
}
-(void)query
{
char *sql = "select * from student;";
//查询结果保存集合
sqlite3_stmt *stmt= NULL;
int result = sqlite3_prepare_v2(db, sql , -1, &stmt, NULL);
if (result == SQLITE_OK) {
NSLog(@"查询语句合法");
while (sqlite3_step(stmt) == SQLITE_ROW) { //按照行进行遍历 直到取完为止
int sid = sqlite3_column_int(stmt, 0); //取当前行出第几列的值
const unsigned char *sname = sqlite3_column_text(stmt, 1);
int sage = sqlite3_column_int(stmt, 2);
NSLog(@"%d,%s,%d",sid,sname,sage);
}
}else {
NSLog(@"查询语句不合法");
}
}