iOS sqlite C語言操作 – iPhone手機開發技術文章 iPhone軟體開發教學課程

利用周六時間看瞭一下關於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

You May Also Like