sql.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "sql.h"
  2. // select count(*) from $table_name where $where;
  3. void sql_count(std::string& sql, const char* table_name, const char* where) {
  4. sql = "select count(*) from ";
  5. sql += table_name;
  6. if (where) {
  7. sql += " where ";
  8. sql += where;
  9. }
  10. sql += ';';
  11. }
  12. // select $keys from $table_name where $where limit $limit order by $column ASC|DESC;
  13. void sql_select(std::string& sql, const char* table_name, const char* keys, const char* where, const KeyVal* options) {
  14. sql = "select ";
  15. if (keys) {
  16. sql += keys;
  17. }
  18. else {
  19. sql += '*';
  20. }
  21. sql += " from ";
  22. sql += table_name;
  23. if (where) {
  24. sql += " where ";
  25. sql += where;
  26. }
  27. if (options) {
  28. for (KeyVal::const_iterator iter = options->begin(); iter != options->end(); ++iter) {
  29. sql += ' ';
  30. sql += iter->first;
  31. sql += ' ';
  32. sql += iter->second;
  33. }
  34. }
  35. sql += ';';
  36. }
  37. // insert into $table_name ($keys) values ($values);
  38. void sql_insert(std::string& sql, const char* table_name, const char* keys, const char* values) {
  39. sql = "insert into ";
  40. sql += table_name;
  41. if (keys) {
  42. sql += " (";
  43. sql += keys;
  44. sql += ')';
  45. }
  46. if (values) {
  47. sql += " values ";
  48. sql += '(';
  49. sql += values;
  50. sql += ')';
  51. }
  52. sql += ';';
  53. }
  54. // update $table_name set $set where $where;
  55. void sql_update(std::string& sql, const char* table_name, const char* set, const char* where) {
  56. sql = "update ";
  57. sql += table_name;
  58. if (set) {
  59. sql += " set ";
  60. sql += set;
  61. }
  62. if (where) {
  63. sql += " where ";
  64. sql += where;
  65. }
  66. sql += ';';
  67. }
  68. // delete from $table_name where $where;
  69. void sql_delete(std::string& sql, const char* table_name, const char* where) {
  70. sql = "delete from ";
  71. sql += table_name;
  72. if (where) {
  73. sql += " where ";
  74. sql += where;
  75. }
  76. sql += ';';
  77. }