database_connection.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. #ifndef DB_CONN_H
  18. #define DB_CONN_H
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <string>
  23. #include <stdint.h>
  24. // mysql include files
  25. #define list_add my_list_add
  26. #include "mysql.h"
  27. #undef list_add
  28. struct DBHost {
  29. char Host[110];
  30. int Port;
  31. char User[64];
  32. char Password[128];
  33. unsigned int ConnTimeout;
  34. unsigned int ReadTimeout;
  35. unsigned int WriteTimeout;
  36. char OptionFile[256];
  37. };
  38. class CDBConn {
  39. private:
  40. DBHost DBConfig;
  41. int Connected;
  42. MYSQL Mysql;
  43. char achErr[400];
  44. int db_err;
  45. int use_matched;
  46. std::string s_charac_set;
  47. public:
  48. MYSQL_RES *Res;
  49. MYSQL_ROW Row;
  50. int res_num;
  51. int need_free;
  52. protected:
  53. int Connect(const char *DBName);
  54. public:
  55. CDBConn();
  56. CDBConn(const DBHost *Host);
  57. static int get_client_version(void);
  58. void do_config(const DBHost *Host);
  59. void use_matched_rows(void);
  60. const char *get_err_msg();
  61. int get_err_no();
  62. int get_raw_err_no();
  63. int Open();
  64. int Open(const char *DBName);
  65. int Close();
  66. int do_ping(void);
  67. int do_query(const char *SQL); // connect db if needed
  68. int do_query(const char *DBName,
  69. const char *SQL); // connect db if needed
  70. int begin_work();
  71. int do_commit();
  72. int roll_back();
  73. int64_t affected_rows();
  74. const char *result_info();
  75. uint64_t insert_id();
  76. uint32_t escape_string(char To[], const char *From);
  77. uint32_t escape_string(char To[], const char *From, int Len);
  78. int64_t get_variable(const char *v);
  79. int use_result();
  80. int fetch_row();
  81. int free_result();
  82. inline unsigned long *get_lengths(void)
  83. {
  84. return mysql_fetch_lengths(Res);
  85. }
  86. const std::string& GetCharacSet() const { return s_charac_set;};
  87. ~CDBConn();
  88. };
  89. #endif