You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.6 KiB

2 years ago
  1. /**
  2. * Example implemented from here https://www.tutorialspoint.com/sqlite/sqlite_update_query.htm
  3. */
  4. #include <sqlite_orm/sqlite_orm.h>
  5. #include <iostream>
  6. #include <memory>
  7. using std::cout;
  8. using std::endl;
  9. struct Employee {
  10. int id;
  11. std::string name;
  12. int age;
  13. std::string address;
  14. double salary;
  15. };
  16. inline auto initStorage(const std::string& path) {
  17. using namespace sqlite_orm;
  18. return make_storage(path,
  19. make_table("COMPANY",
  20. make_column("ID", &Employee::id, primary_key()),
  21. make_column("NAME", &Employee::name),
  22. make_column("AGE", &Employee::age),
  23. make_column("ADDRESS", &Employee::address),
  24. make_column("SALARY", &Employee::salary)));
  25. }
  26. using Storage = decltype(initStorage(""));
  27. static std::unique_ptr<Storage> stor;
  28. int main(int, char**) {
  29. stor = std::make_unique<Storage>(initStorage("update.sqlite"));
  30. stor->sync_schema();
  31. stor->remove_all<Employee>();
  32. // insert initial values
  33. stor->replace(Employee{1, "Paul", 32, "California", 20000.0});
  34. stor->replace(Employee{2, "Allen", 25, "Texas", 15000.0});
  35. stor->replace(Employee{3, "Teddy", 23, "Norway", 20000.0});
  36. stor->replace(Employee{4, "Mark", 25, "Rich-Mond", 65000.0});
  37. stor->replace(Employee{5, "David", 27, "Texas", 85000.0});
  38. stor->replace(Employee{6, "Kim", 22, "South-Hall", 45000.0});
  39. stor->replace(Employee{7, "James", 24, "Houston", 10000.0});
  40. // show 'COMPANY' table contents
  41. for(auto& employee: stor->iterate<Employee>()) {
  42. cout << stor->dump(employee) << endl;
  43. }
  44. cout << endl;
  45. // 'UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6'
  46. auto employee6 = stor->get<Employee>(6);
  47. employee6.address = "Texas";
  48. stor->update(
  49. employee6); // actually this call updates all non-primary-key columns' values to passed object's fields
  50. // show 'COMPANY' table contents again
  51. for(auto& employee: stor->iterate<Employee>()) {
  52. cout << stor->dump(employee) << endl;
  53. }
  54. cout << endl;
  55. // 'UPDATE COMPANY SET ADDRESS = 'Texas', SALARY = 20000.00 WHERE AGE < 30'
  56. using namespace sqlite_orm;
  57. stor->update_all(set(c(&Employee::address) = "Texas", c(&Employee::salary) = 20000.00),
  58. where(c(&Employee::age) < 30));
  59. // show 'COMPANY' table contents one more time
  60. for(auto& employee: stor->iterate<Employee>()) {
  61. cout << stor->dump(employee) << endl;
  62. }
  63. cout << endl;
  64. return 0;
  65. }