Sqlite 增删改查


- (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(@"查询语句不合法");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值