iOS SQLite学习笔记

@bingoogolapple 2015-08-07 10:24:10发表于 bingoogolapple/bingoogolapple.github.io iOS

/**
 初始化数据库
 */
- (void)setupDb
{
    // 打开数据库(连接数据库)
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];
    // 如果数据库文件不存在, 系统会自动创建文件自动初始化数据库
    int status = sqlite3_open(filename.UTF8String, &_db);
    if (status == SQLITE_OK) { // 打开成功
        NSLog(@"打开数据库成功");

        // 创表
        const char *sql = "CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, name text NOT NULL, price real);";
        char *errmsg = NULL;
        sqlite3_exec(self.db, sql, NULL, NULL, &errmsg);
        if (errmsg) {
            NSLog(@"创表失败--%s", errmsg);
        }
    } else { // 打开失败
        NSLog(@"打开数据库失败");
    }
}

/**
 查询数据
 */
- (void)setupData
{
    const char *sql = "SELECT name,price FROM t_shop;";
    // stmt是用来取出查询结果的
    sqlite3_stmt *stmt = NULL;
    // 准备
    int status = sqlite3_prepare_v2(self.db, sql, -1, &stmt, NULL);
    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确
        while (sqlite3_step(stmt) == SQLITE_ROW) { // 成功取出一条数据
            const char *name = (const char *)sqlite3_column_text(stmt, 0);
            const char *price = (const char *)sqlite3_column_text(stmt, 1);

            HMShop *shop = [[HMShop alloc] init];
            shop.name = [NSString stringWithUTF8String:name];
            shop.price = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
        }
    }
}

- (IBAction)insert {
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_shop(name, price) VALUES ('%@', %f);", self.nameField.text, self.priceField.text.doubleValue];
    sqlite3_exec(self.db, sql.UTF8String, NULL, NULL, NULL);

    // 刷新表格
    HMShop *shop = [[HMShop alloc] init];
    shop.name = self.nameField.text;
    shop.price = self.priceField.text;
    [self.shops addObject:shop];
    [self.tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.shops removeAllObjects];

    NSString *sql = [NSString stringWithFormat:@"SELECT name,price FROM t_shop WHERE name LIKE '%%%@%%' OR  price LIKE '%%%@%%' ;", searchText, searchText];
    // stmt是用来取出查询结果的
    sqlite3_stmt *stmt = NULL;
    // 准备
    int status = sqlite3_prepare_v2(self.db, sql.UTF8String, -1, &stmt, NULL);
    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确
        while (sqlite3_step(stmt) == SQLITE_ROW) { // 成功取出一条数据
            const char *name = (const char *)sqlite3_column_text(stmt, 0);
            const char *price = (const char *)sqlite3_column_text(stmt, 1);

            HMShop *shop = [[HMShop alloc] init];
            shop.name = [NSString stringWithUTF8String:name];
            shop.price = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
        }
    }

    [self.tableView reloadData];
}

/**
 NSMutableString *sql = [NSMutableString string];

 for (int i = 0; i<1000; i++) {
 NSString *name = [NSString stringWithFormat:@"iPhone%d", i];
 double price = arc4random() % 10000 + 100;
 int leftCount = arc4random() % 1000;
 [sql appendFormat:@"insert into t_shop(name, price, left_count) values ('%@', %f, %d);\n", name, price, leftCount];
 }

 [sql writeToFile:@"/Users/apple/Desktop/shops.sql" atomically:YES encoding:NSUTF8StringEncoding error:nil];
 */

1.打开数据库
int sqlite3_open(
const char _filename, // 数据库的文件路径
sqlite3 *_ppDb // 数据库实例
);

2.执行任何SQL语句
int sqlite3_exec(
sqlite3_, // 一个打开的数据库实例
const char *sql, // 需要执行的SQL语句
int (callback)(void,int,char__,char__), // SQL语句执行完毕后的回调
void *, // 回调函数的第1个参数
char *_errmsg // 错误信息
);

3.检查SQL语句的合法性(查询前的准备)
int sqlite3_prepare_v2(
sqlite3 _db, // 数据库实例
const char *zSql, // 需要检查的SQL语句
int nByte, // SQL语句的最大字节长度
sqlite3_stmt *_ppStmt, // sqlite3_stmt实例,用来获得数据库数据
const char **pzTail
);

4.查询一行数据
int sqlite3_step(sqlite3_stmt*); // 如果查询到一行数据,就会返回SQLITE_ROW

5.利用stmt获得某一字段的值(字段的下标从0开始)
double sqlite3_column_double(sqlite3_stmt_, int iCol); // 浮点数据
int sqlite3_column_int(sqlite3_stmt_, int iCol); // 整型数据
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt_, int iCol); // 长整型数据
const void *sqlite3_column_blob(sqlite3_stmt_, int iCol); // 二进制文本数据
const unsigned char sqlite3_column_text(sqlite3_stmt, int iCol); // 字符串数据