数据库增删改查代码

-(NSArray *)getAllStundets

{

    //1创建临时集合 存储学生信息

    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:20];

    //2打开数据库

    sqlite3 *sql = [DBManager openDB];

    //3执行命令语句

    sqlite3_stmt *stmt;

    //4预处理操作 查询表里的所有记录

    if (sql!=nil) {

        

    

    int num = sqlite3_prepare_v2(sql, "select * from student", -1, &stmt, nil);

    //5是否可以操作表

    if (num == SQLITE_OK) {

        //6循环便利表中的记录 即检索每一行

        while ( SQLITE_ROW == sqlite3_step(stmt)) {

            //7根据指定索引找到指定行的信息

            int stuid = sqlite3_column_int(stmt, 0);

            NSString *stuname = [NSString stringWithFormat:@"%s",sqlite3_column_text(stmt, 1)];

             NSString *stupwd = [NSString stringWithFormat:@"%s",sqlite3_column_text(stmt, 2)];

            //8创建临时学生类型对象

            Student *stu = [[Student alloc] init];

            //9将数据表中的信息 存储到实体类的属性中

            stu.stuid = stuid;

            stu.stuname = stuname;

            stu.stupwd = stupwd;

            //将试题类型添加到数组中

            

           

            [arr addObject:stu];

            

        }

    }

    }

    //10返回集合信息,即一组 学生类型的集合

    

    return arr;

}

-(BOOL)addStudents:(Student *)stu

{

    BOOL bol = NO;

    sqlite3 *sql = [DBManager openDB];

    sqlite3_stmt *stmt;

    int num  = sqlite3_prepare_v2(sql, "insert into student(stuname,stupwd) values(?,?)", -1, &stmt, nil);

    sqlite3_bind_text(stmt, 1, [stu.stuname UTF8String], -1, nil);

    sqlite3_bind_text(stmt, 2, [stu.stupwd UTF8String], -1, nil);

    if (num == SQLITE_OK) {

        if (SQLITE_DONE == sqlite3_step(stmt)) {

            bol = YES;

        }

    }

    return bol;

}

-(BOOL)updateStudents:(Student *)stu

{

    BOOL bol = NO;

    sqlite3 *sql = [DBManager openDB];

    sqlite3_stmt *stmt;

    int ret = sqlite3_prepare_v2(sql, "update student set stuname = ?, stupwd = ? where stuid = ? ", -1, &stmt, nil);

    

    sqlite3_bind_text(stmt, 1, [stu.stuname UTF8String], -1, nil);

     sqlite3_bind_text(stmt, 2, [stu.stupwd UTF8String], -1, nil);

    sqlite3_bind_int(stmt, 3, stu.stuid);

    if (ret == SQLITE_OK) {

        if (SQLITE_DONE == sqlite3_step(stmt)) {

            bol = YES;

        }

    }

    

    return bol;

}

-(BOOL)removeStundets:(Student *)stu

{

    BOOL bol = NO;

    sqlite3 *sql = [DBManager openDB];

    sqlite3_stmt *stmt;

    int ret = sqlite3_prepare_v2(sql, "delete from student where stuname = ? or stupwd = ? or stuid = ?", -1, &stmt, nil);

    sqlite3_bind_text(stmt, 1, [stu.stuname UTF8String], -1, nil);

    sqlite3_bind_text(stmt, 2, [stu.stupwd UTF8String], -1, nil);

    sqlite3_bind_int(stmt, 3, stu.stuid);

    if (ret == SQLITE_OK) {

        if (SQLITE_DONE == sqlite3_step(stmt)) {

            bol = YES;

        }

    }

    return bol;

}

原文地址:https://www.cnblogs.com/wujie123/p/5313469.html