· 5 years ago · Jun 21, 2020, 04:48 PM
1sqlconnection.h
2
3#ifndef SQLCONNECTION_H
4#define SQLCONNECTION_H
5
6#include <iostream>
7#include <string>
8
9#include <mysql/my_global.h>
10#include <mysql/mysql.h>
11
12using namespace std;
13using std::string;
14
15template < typename SQLType >
16
17class SQLConnection
18{
19public:
20 SQLConnection();
21 static bool CheckInternet();
22 static MYSQL *Connect(const char *host,
23 const char *dbName,
24 const char *username,
25 const char *password);
26 static void CreateUserTable (MYSQL *con, string tableName);
27 static void DeleteUserTable (MYSQL *con, string tableName);
28 static SQLType GetVariable (MYSQL *con, const char *variable);
29 static void SetVariable (MYSQL *con, const char *variable, const char *value);
30private:
31 static void finish_with_error (MYSQL *con);
32};
33
34#endif // SQLCONNECTION_H
35
36sqlconnection.cpp
37
38#include "sqlconnection.h"
39#include <QCryptographicHash>
40
41SQLConnection::SQLConnection()
42{
43
44}
45
46void SQLConnection::finish_with_error(MYSQL *con)
47{
48 cerr << "[MySQL] " << mysql_error(con) << endl;
49 mysql_close(con);
50}
51
52bool SQLConnection::CheckInternet()
53{
54 FILE *output;
55
56 if(!(output = popen("/sbin/route -n | grep -c '^0\\.0\\.0\\.0'","r")))
57 {
58 return false;
59 }
60
61 unsigned int i;
62 fscanf(output, "%u", &i);
63 pclose(output);
64
65 if(i == 1)
66 return true;
67 else
68 return false;
69}
70
71MYSQL *SQLConnection::Connect(const char *db_host,
72 const char *db_name,
73 const char *db_user,
74 const char *db_password)
75{
76 MYSQL *con = mysql_init(NULL);
77 if (con == NULL) {
78 cerr << "[MySQL] " << mysql_error(con) << endl;
79 return NULL;
80 }
81 if (mysql_real_connect(con, db_host, db_user, db_password, db_name, 0, NULL, 0) == NULL) {
82 finish_with_error(con);
83 return NULL;
84 }
85 cout << "[MySQL] Connected successfully!\n";
86 return con;
87}
88s
89void SQLConnection::CreateUserTable(MYSQL *con, string tableName){
90 string query = "CREATE TABLE IF NOT EXISTS " + tableName + "(task_id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(24) NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(48) NOT NULL, userID INT NOT NULL) ENGINE=INNODB;";
91 if (mysql_query(con, query.c_str())){
92 finish_with_error(con);
93 } else
94 cout << "[MySQL] Table created\n";
95}
96
97void SQLConnection::DeleteUserTable(MYSQL *con, string tableName){
98
99}
100
101void SQLConnection::SetVariable(MYSQL *con, const char *variable, const char *value){
102
103}
104
105void SQLConnection::GetVariable(MYSQL *con, const char *variable, const char *value){
106
107}