前端之家收集整理的这篇文章主要介绍了
SQLite创建表并添加数据,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
- - (void)viewDidLoad {
- [super viewDidLoad];
- //创建表
- [self creatTable];
- //插入数据
- [self insertTable];
- }
-
- // -----------------------创建一个表--------------------
- - (void)creatTable
- {
- // 1.创建一个数据库对象
- sqlite3 *sqlite3 = nil;
-
- // 2.数据库的路径
- NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MysqLite.db"];
-
- // 3.打开数据库 (通过指定路径打开数据库文件,如果没有就创建)
- int result = sqlite3_open([path UTF8String],&sqlite3);
- if (result != sqlITE_OK) {
- NSLog(@"数据库打开失败!");
- return;
- }
-
- // 4.创建sql语句
- NSString *sql = @"CREATE TABLE Students (id integer PRIMARY KEY,name text)";
-
- // 5.执行sql语句
- char *error = NULL;
- result = sqlite3_exec(sqlite3,[sql UTF8String],NULL,&error);
- if (result != sqlITE_OK) {
- NSLog(@"执行sql语句失败!");
- // 6.关闭数据库
- sqlite3_close(sqlite3);
- return;
- }
- // 6.关闭数据库
- sqlite3_close(sqlite3);
- }
-
- // -------------------------插入数据------------------------
- - (void)insertTable
- {
- // 1.创建一个数据库对象
- sqlite3 *sqlite3 = nil;
-
- // 2.数据库的路径
- NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MysqLite.db"];
-
- // 3.打开数据库 (通过指定路径打开数据库文件,如果没有就创建)
- int result = sqlite3_open([path UTF8String],&sqlite3);
- if (result != sqlITE_OK) {
- NSLog(@"数据库打开失败!");
- return;
- }
-
- // 4.创建sql语句
- // insert into students(id,name) values('123456','李斯')
- NSString *sql = @"insert into students(id,name) values(?,?)";
-
- // 5.编译sql语句
- // 创建一个数据句柄对象
- sqlite3_stmt *stmt = nil;
- result = sqlite3_prepare_v2(sqlite3,-1,&stmt,nil);
- if (result != sqlITE_OK) {
- NSLog(@"编译失败");
- // 关闭数据库
- sqlite3_close(sqlite3);
- return;
- }
-
- // 6.绑定数据到数据句柄里面
- sqlite3_bind_int(stmt,1,123457);
- sqlite3_bind_text(stmt,2,"张三",nil);
-
- // 7.执行数据句柄的操作
- result = sqlite3_step(stmt);
- if (result == sqlITE_ERROR || result == sqlITE_MISUSE) {
- NSLog(@"插入失败");
- // 关闭数据句柄
- sqlite3_finalize(stmt);
- // 关闭数据库
- sqlite3_close(sqlite3);
- return ;
- }
-
- // 8.执行成功
- NSLog(@"插入成功");
- // 关闭数据句柄
- sqlite3_finalize(stmt);
- // 关闭数据库
- sqlite3_close(sqlite3);
-
-
- }