Guest User

Untitled

a guest
Oct 18th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. /*
  2. * Example to connect to MariaDB(MySQL)
  3. */
  4. #include <iostream>
  5. #include <mysql/mysql.h> // require libmysqlclient-dev
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. /*
  11. * [CLASS] Process
  12. */
  13. class Proc
  14. {
  15. const char* MY_HOSTNAME;
  16. const char* MY_DATABASE;
  17. const char* MY_USERNAME;
  18. const char* MY_PASSWORD;
  19. const char* MY_SOCKET;
  20. enum {
  21. MY_PORT_NO = 3306,
  22. MY_OPT = 0
  23. };
  24. MYSQL *conn;
  25. MYSQL_RES *res;
  26. MYSQL_ROW row;
  27.  
  28. public:
  29. Proc(); // Constructor
  30. bool execMain(); // Main Process
  31. };
  32.  
  33. /*
  34. * Proc - Constructor
  35. */
  36. Proc::Proc()
  37. {
  38. // Initialize constants
  39. MY_HOSTNAME = "localhost";
  40. MY_DATABASE = "mysql";
  41. MY_USERNAME = "root";
  42. MY_PASSWORD = "7621mizuiko3701";
  43. MY_SOCKET = NULL;
  44.  
  45. }
  46.  
  47. /*
  48. * Main Process
  49. */
  50. bool Proc::execMain()
  51. {
  52. try {
  53. // Format a MySQL object
  54. conn = mysql_init(NULL);
  55.  
  56. // Establish a MySQL connection
  57. if (!mysql_real_connect(
  58. conn,
  59. MY_HOSTNAME, MY_USERNAME,
  60. MY_PASSWORD, MY_DATABASE,
  61. MY_PORT_NO, MY_SOCKET, MY_OPT)) {
  62. cerr << mysql_error(conn) << endl;
  63. return false;
  64. }
  65.  
  66. // Execute a sql statement
  67. if (mysql_query(conn, "SHOW TABLES")) {
  68. cerr << mysql_error(conn) << endl;
  69. return false;
  70. }
  71.  
  72. // Get a result set
  73. res = mysql_use_result(conn);
  74.  
  75. // Fetch a result set
  76. cout << "* MySQL - SHOW TABLES in `"
  77. << MY_DATABASE << "`" << endl;
  78. while ((row = mysql_fetch_row(res)) != NULL)
  79. cout << row[0] << endl;
  80.  
  81. // Release memories
  82. mysql_free_result(res);
  83.  
  84. // Close a MySQL connection
  85. mysql_close(conn);
  86. } catch (char *e) {
  87. cerr << "[EXCEPTION] " << e << endl;
  88. return false;
  89. }
  90. return true;
  91. }
  92.  
  93. /*
  94. * Execution
  95. */
  96. int main(){
  97. try {
  98. Proc objMain;
  99. bool bRet = objMain.execMain();
  100. if (!bRet) cout << "ERROR!" << endl;
  101. } catch (char *e) {
  102. cerr << "[EXCEPTION] " << e << endl;
  103. return 1;
  104. }
  105. return 0;
  106. }
Add Comment
Please, Sign In to add comment