· 8 years ago · Feb 23, 2018, 05:20 PM
1public sealed class DatabaseManager
2{
3 private static Logger _log = new Logger("DatabaseManager");
4
5 private static volatile DatabaseManager INSTANCE;
6 private static object syncRoot = new Object();
7
8 private static MySqlConnection _connection;
9
10 private static string host = "192.168.1.100";
11 private static string database = "test";
12 private static string user = "root";
13 private static string password = "2223322";
14 private static string _connectionString = "Data Source=" + host + ";Database=" + database + ";User ID=" + user + ";Password=" + password + ";Character Set=utf8";
15
16 private DatabaseManager()
17 {
18 // Do nothing.
19 }
20
21 public void init()
22 {
23 _connection = new MySqlConnection(_connectionString);
24
25 try
26 {
27 _connection.Open();
28
29 using (MySqlCommand command = _connection.CreateCommand())
30 {
31 command.CommandText = "CREATE TABLE IF NOT EXISTS connection_test_table (`a` char(1) DEFAULT NULL)";
32 command.ExecuteNonQuery();
33 }
34
35 _connection.Close();
36
37 _log.info("Database Pool activated successful.");
38 }
39 catch (Exception e)
40 {
41 _log.error("Attempting to connect to: " + database + "@" + host + "...", e.Message, e.StackTrace);
42 }
43 }
44
45 public void shutdown()
46 {
47 try
48 {
49 _connection.Close();
50 }
51 catch (Exception e)
52 {
53 _log.error("Error while closing Database connection.", e.Message, e.StackTrace);
54 }
55
56 try
57 {
58 _connection = null;
59 }
60 catch (Exception e)
61 {
62 _log.error("Errur while destroing connection object.", e.Message, e.StackTrace);
63 }
64 }
65
66 public MySqlConnection getConnection()
67 {
68 while (_connection == null)
69 {
70 if (_connection == null)
71 {
72 _connection = new MySqlConnection(_connectionString);
73 _connection.Open();
74 }
75 }
76
77 if (_connection.State != ConnectionState.Open)
78 _connection.Open();
79
80 return _connection;
81 }
82
83 public static DatabaseManager getInstance
84 {
85 get
86 {
87 if (INSTANCE == null)
88 {
89 lock (syncRoot)
90 {
91 if (INSTANCE == null)
92 INSTANCE = new DatabaseManager();
93 }
94 }
95
96 return INSTANCE;
97 }
98 }
99}
100
101using (MySqlCommand command = DatabaseManager.getInstance.getConnection().CreateCommand())
102{
103 command.CommandText = "TRUNCATE TABLE connection_test_table";
104 command.ExecuteNonQuery();
105}
106
107DatabaseManager.getInstance.shutdown();