41_kvdb.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <sqlite3.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. int main()
  5. {
  6. sqlite3 *db;
  7. sqlite3_open(":memory:", &db);
  8. sqlite3_exec(db, "CREATE TABLE kvdb(id TEXT PRIMARY KEY,val TEXT)", 0, 0, 0);
  9. printf("Welcome to the simplest key-value database\n");
  10. while (1)
  11. {
  12. char tmp[1024];
  13. printf("What do you want to do?\n");
  14. printf("Enter P to [P]ut, G to [G]et or L to [L]ist\n");
  15. printf("Or enter Q to [Q]uit\n");
  16. gets(tmp);
  17. if (!strcmp(tmp, "P"))
  18. {
  19. char key[1024];
  20. char data[1024];
  21. printf("Enter key: ");
  22. gets(key);
  23. printf("Enter data: ");
  24. gets(data);
  25. sqlite3_stmt *ins;
  26. sqlite3_prepare_v2(db, "INSERT OR REPLACE INTO kvdb VALUES (?,?)", -1, &ins, NULL);
  27. sqlite3_bind_text(ins, 1, key, -1, SQLITE_STATIC);
  28. sqlite3_bind_text(ins, 2, data, -1, SQLITE_STATIC);
  29. sqlite3_step(ins);
  30. sqlite3_finalize(ins);
  31. continue;
  32. }
  33. if (!strcmp(tmp, "G"))
  34. {
  35. char key[1024];
  36. printf("Enter key: ");
  37. gets(key);
  38. sqlite3_stmt *res;
  39. sqlite3_prepare_v2(db, "SELECT val FROM kvdb WHERE id=?", -1, &res, NULL);
  40. sqlite3_bind_text(res, 1, key, -1, SQLITE_STATIC);
  41. int rc = sqlite3_step(res);
  42. if (rc != SQLITE_DONE)
  43. {
  44. printf("Your data: %s\n", sqlite3_column_text(res, 0));
  45. }
  46. else
  47. printf("No such key\n");
  48. sqlite3_finalize(res);
  49. continue;
  50. }
  51. if (!strcmp(tmp, "L"))
  52. {
  53. sqlite3_stmt *res;
  54. sqlite3_prepare_v2(db, "SELECT * FROM kvdb", -1, &res, NULL);
  55. printf("DB contents:\n");
  56. int rc = sqlite3_step(res);
  57. while (rc != SQLITE_DONE)
  58. {
  59. printf("%s: %s\n", sqlite3_column_text(res, 0), sqlite3_column_text(res, 1));
  60. rc = sqlite3_step(res);
  61. }
  62. sqlite3_finalize(res);
  63. continue;
  64. }
  65. if (!strcmp(tmp, "Q"))
  66. {
  67. printf("Bye\n");
  68. break;
  69. }
  70. }
  71. sqlite3_close(db);
  72. return 0;
  73. }