main.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // This is a test program for sqlite3.
  2. // We take it from rcore-os/arceos, thanks to @rcore-os community.
  3. #include <sqlite3.h>
  4. #include <stddef.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. int callback(void *NotUsed, int argc, char **argv, char **azColName)
  8. {
  9. NotUsed = NULL;
  10. for (int i = 0; i < argc; ++i) {
  11. printf("%s = %s\n", azColName[i], (argv[i] ? argv[i] : "NULL"));
  12. }
  13. printf("\n");
  14. return 0;
  15. }
  16. void exec(sqlite3 *db, char *sql)
  17. {
  18. printf("sqlite exec:\n %s\n", sql);
  19. char *errmsg = NULL;
  20. int rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
  21. if (rc != SQLITE_OK) {
  22. printf("sqlite exec error: %s\n", errmsg);
  23. }
  24. }
  25. void query(sqlite3 *db, char *sql)
  26. {
  27. printf("sqlite query:\n %s\n", sql);
  28. char *errmsg = NULL;
  29. int rc = sqlite3_exec(db, sql, callback, NULL, &errmsg);
  30. if (rc != SQLITE_OK) {
  31. printf("%s\n", errmsg);
  32. }
  33. }
  34. void query_test(sqlite3 *db, const char *args)
  35. {
  36. puts("======== init user table ========");
  37. exec(db, "create table user("
  38. "id INTEGER PRIMARY KEY AUTOINCREMENT,"
  39. "username TEXT,"
  40. "password TEXT"
  41. ")");
  42. puts("======== insert user 1, 2, 3 into user table ========");
  43. char cmd[256] = {0};
  44. sprintf(cmd,
  45. "insert into user (username, password) VALUES ('%s_1', 'password1'), ('%s_2', "
  46. "'password2'), ('%s_3', 'password3')",
  47. args, args, args);
  48. exec(db, cmd);
  49. puts("======== select all ========");
  50. query(db, "select * from user");
  51. puts("======== select id = 2 ========");
  52. query(db, "select * from user where id = 2");
  53. }
  54. void memory()
  55. {
  56. sqlite3 *db;
  57. printf("sqlite open memory\n");
  58. int ret = sqlite3_open(":memory:", &db);
  59. printf("sqlite open memory status %d \n", ret);
  60. query_test(db, "memory");
  61. }
  62. void file()
  63. {
  64. sqlite3 *db;
  65. int ret = sqlite3_open("file.sqlite", &db);
  66. printf("sqlite open /file.sqlite status %d \n", ret);
  67. if (ret != 0) {
  68. printf("sqlite open error");
  69. return;
  70. }
  71. query_test(db, "file");
  72. sqlite3_close(db);
  73. }
  74. int main()
  75. {
  76. printf("sqlite version: %s\n", sqlite3_libversion());
  77. memory();
  78. file();
  79. return 0;
  80. }