SQLite创建表并添加数据

前端之家收集整理的这篇文章主要介绍了SQLite创建表并添加数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. - (void)viewDidLoad {
  2. [super viewDidLoad];
  3. //创建表
  4. [self creatTable];
  5. //插入数据
  6. [self insertTable];
  7. }
  8.  
  9. // -----------------------创建一个表--------------------
  10. - (void)creatTable
  11. {
  12. // 1.创建一个数据库对象
  13. sqlite3 *sqlite3 = nil;
  14. // 2.数据库的路径
  15. NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MysqLite.db"];
  16. // 3.打开数据库 (通过指定路径打开数据库文件,如果没有就创建)
  17. int result = sqlite3_open([path UTF8String],&sqlite3);
  18. if (result != sqlITE_OK) {
  19. NSLog(@"数据库打开失败!");
  20. return;
  21. }
  22. // 4.创建sql语句
  23. NSString *sql = @"CREATE TABLE Students (id integer PRIMARY KEY,name text)";
  24. // 5.执行sql语句
  25. char *error = NULL;
  26. result = sqlite3_exec(sqlite3,[sql UTF8String],NULL,&error);
  27. if (result != sqlITE_OK) {
  28. NSLog(@"执行sql语句失败!");
  29. // 6.关闭数据库
  30. sqlite3_close(sqlite3);
  31. return;
  32. }
  33. // 6.关闭数据库
  34. sqlite3_close(sqlite3);
  35. }
  36.  
  37. // -------------------------插入数据------------------------
  38. - (void)insertTable
  39. {
  40. // 1.创建一个数据库对象
  41. sqlite3 *sqlite3 = nil;
  42. // 2.数据库的路径
  43. NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MysqLite.db"];
  44. // 3.打开数据库 (通过指定路径打开数据库文件,如果没有就创建)
  45. int result = sqlite3_open([path UTF8String],&sqlite3);
  46. if (result != sqlITE_OK) {
  47. NSLog(@"数据库打开失败!");
  48. return;
  49. }
  50. // 4.创建sql语句
  51. // insert into students(id,name) values('123456','李斯')
  52. NSString *sql = @"insert into students(id,name) values(?,?)";
  53. // 5.编译sql语句
  54. // 创建一个数据句柄对象
  55. sqlite3_stmt *stmt = nil;
  56. result = sqlite3_prepare_v2(sqlite3,-1,&stmt,nil);
  57. if (result != sqlITE_OK) {
  58. NSLog(@"编译失败");
  59. // 关闭数据库
  60. sqlite3_close(sqlite3);
  61. return;
  62. }
  63. // 6.绑定数据到数据句柄里面
  64. sqlite3_bind_int(stmt,1,123457);
  65. sqlite3_bind_text(stmt,2,"张三",nil);
  66. // 7.执行数据句柄的操作
  67. result = sqlite3_step(stmt);
  68. if (result == sqlITE_ERROR || result == sqlITE_MISUSE) {
  69. NSLog(@"插入失败");
  70. // 关闭数据句柄
  71. sqlite3_finalize(stmt);
  72. // 关闭数据库
  73. sqlite3_close(sqlite3);
  74. return ;
  75. }
  76. // 8.执行成功
  77. NSLog(@"插入成功");
  78. // 关闭数据句柄
  79. sqlite3_finalize(stmt);
  80. // 关闭数据库
  81. sqlite3_close(sqlite3);
  82. }

猜你在找的Sqlite相关文章