首页 > 代码库 > iOS sqlite C语言操作

iOS sqlite C语言操作

利用周六时间看了一下关于sqlite的知识,在这记录一下。看的传智播客视频

对数据的操作基本上就是增删改查:

static sqlite3 *db; //声明一个数据库
@implementation XSDBOperator

+ (void)initialize
{
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"student.sqlite"];  //数据库文件路径
    //如果文件存在,则打开数据库文件,如果不存在则创建,并且打开
    int result = sqlite3_open(filename.UTF8String, &db); //
    //判断是否打开数据库成功
    if (result == SQLITE_OK) {
        NSLog(@"打开数据库成功");
    }
    else
    {
        NSLog(@"打开失败");
    }
}
#pragma mark - 创建数据库表
+(BOOL)creatTable
{
    char *sql = "create table if not exists t_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) {
        return YES;
    }
    else
    {
        NSLog(@"创建表失败,失败原因:%s",errorMesg);
        return NO;
    }
}

+(BOOL)insert
{
    char *sql = "insert into t_table (name,age) values('jack',20)";
    char *errorMesg = NULL;
    int result = sqlite3_exec(db, sql , NULL, NULL, &errorMesg);
    if (result == SQLITE_OK) {
        return YES;
    }
    else
    {
        NSLog(@"插入数据失败,失败原因:%s",errorMesg);
        return NO;
    }
}

+ (BOOL)updata
{
    char *sql = "updata t_table set age = 12";
    char *errorMesg = NULL;
    int result = sqlite3_exec(db, sql , NULL, NULL, &errorMesg);
    if (result == SQLITE_OK) {
        return YES;
    }
    else
    {
        NSLog(@"更新数据失败,失败原因:%s",errorMesg);
        return NO;
    }
}

+ (void)query
{
    char *sql = "select id,name,age from t_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(@"查询语句不合法");
    }
}
@end


iOS sqlite C语言操作