iOS中sqlite的基本使用

时间:2022-07-08 23:03:35
// 初始化数据库
- (void)setupDb
{
// 开发数据库(连接数据库)
NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];

// filename.UTF8String 直接把OC转成C

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(@"创建数据库失败");
} else {
NSLog(@"创建数据库成功");
}

} else { // 打开数据库失败
NSLog(@"打开数据库失败");

}
}
// 查询数据- (void)setupData{    const char *sql = "SELECT name,price FROM t_shop;";    // 用来取查询结果的    sqlite3_stmt *stmt = NULL;    // 准备    int status = sqlite3_prepare_v2(self.db, sql, -1, &stmt, NULL);    if (status == SQLITE_OK) {  // 准备成功        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);                        JYShop *shop = [[JYShop alloc] init];            shop.name = [NSString stringWithUTF8String:name];            shop.price = [NSString stringWithUTF8String:price];            [self.shops addObject:shop];        }    }}

- (IBAction)insert {
// const char *sql = "INSERT INTO t_shop(name, price) VALUES('','');";

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);

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