zoukankan      html  css  js  c++  java
  • SQLite3

    记录一个基础的IOS下SQLite的例子:

    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *filename = @"test-db";
        NSString *dictionary = [paths objectAtIndex:0];
        NSString *dbPaths = [dictionary stringByAppendingPathComponent:filename];
        int result = sqlite3_open([dbPaths UTF8String], &_db);
        
        char *errMsg;
        
        const char *sql_create_stmt = "CREATE TABLE t_user(username varchar(50), password varchar(50));";
        
        if(result == SQLITE_OK){
            
            if (sqlite3_exec(_db, sql_create_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table: %s", errMsg);
                return;
            }
            
        }else{
            NSLog(@"Failed to open database");
            return;
        }
        
        const char *sql_insert_stmt1 = "INSERT INTO t_user(username, password) VALUES('fredric','123')";
        const char *sql_insert_stmt2 = "INSERT INTO t_user(username, password) VALUES('sinny','123')";
        
        if(sqlite3_exec(_db, sql_insert_stmt1, NULL, NULL, &errMsg) != SQLITE_OK){
            NSLog(@"Failed to insert table");
        }
        
        if(sqlite3_exec(_db, sql_insert_stmt2, NULL, NULL, &errMsg) != SQLITE_OK){
            NSLog(@"Failed to insert table");
        }
        
        const char *sql_select_stmt = "SELECT * FROM t_user";
        sqlite3_stmt *stemt = NULL;
    
        sqlite3_prepare_v2(_db, sql_select_stmt, -1, &stemt, NULL);
        // 判断有没有查询结果
        while (sqlite3_step(stemt) == SQLITE_ROW) {
            // 取出第一个字段的查询得结果
            const unsigned char *username = sqlite3_column_text(stemt, 0);
            const unsigned char *password = sqlite3_column_text(stemt, 1);
            
            NSLog(@"%s %s", username, password);
        }
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end

    执行结果:

    2016-04-16 11:12:19.693 ios20[1628:89155] fredric 123

    2016-04-16 11:12:19.694 ios20[1628:89155] sinny 123

  • 相关阅读:
    egrep 正则邮箱
    centos 安装编译时常见错误总结
    线上系统和冷备系统同步单个表数据
    nagios微信报警配置
    saltstack批量加用户脚本
    阿里云服务器迁移流程
    HDU 4912 LCA + 贪心
    HDU 5242 树链剖分思想的贪心
    洛谷P3328(bzoj 4085)毒瘤线段树
    Codeforces 719E (线段树教做人系列) 线段树维护矩阵
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/5397920.html
Copyright © 2011-2022 走看看