【iOS】数据持久化之SQLite3数据库
#import "ViewController.h"
#import <sqlite3.h>
@interface ViewController ()
@property (nonatomic, assign) sqlite3 *database;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self openDatabase];
}
- (void)openDatabase {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"sqlite3"];
if (SQLITE_OK != sqlite3_open([filePath UTF8String], &_database)) {
NSLog(@"数据库打开失败");
}
}
- (void)insertData {
NSString *sqlInsert = @"INSERT INTO Person(Name,Age) VALUES(?,?)";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [sqlInsert UTF8String], -1, &statement, NULL) == SQLITE_OK) {
sqlite3_bind_text(statement, 1, "张三", -1, NULL);
sqlite3_bind_int(statement, 2, 25);
if (sqlite3_step(statement) != SQLITE_DONE) {
NSLog(@"插入数据失败");
}
sqlite3_finalize(statement);
}
}
- (void)queryData {
NSString *sqlQuery = @"SELECT * FROM Person";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [sqlQuery UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
char *name = (char *)sqlite3_column_text(statement, 0);
int age = sqlite3_column_int(statement, 1);
NSLog(@"姓名: %s, 年龄: %d", name, age);
}
sqlite3_finalize(statement);
}
}
- (void)closeDatabase {
sqlite3_close(_database);
}
@end
这段代码示例展示了如何在iOS应用中使用Objective-C语言操作SQLite3数据库。首先在viewDidLoad
中打开数据库,然后定义了插入数据和查询数据的方法。插入数据方法展示了如何准备并执行一条插入SQL语句,查询数据方法展示了如何遍历查询结果并处理每一行数据。最后在dealloc
方法中关闭数据库,确保资源得到释放。
评论已关闭