-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySQLConnectionUtils.cs
More file actions
357 lines (336 loc) · 10.4 KB
/
Copy pathMySQLConnectionUtils.cs
File metadata and controls
357 lines (336 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
using System;
using System.Collections.Generic;
using Microsoft.TeamFoundation.Common;
using MySql.Data.MySqlClient;
using RYCBEditorX.Utils;
using static RYCBEditorX.GlobalConfig;
namespace RYCBEditorX.MySQL;
[System.Security.SecurityCritical]
[System.Reflection.Obfuscation(Exclude = true)]
public class MySQLConnectionUtils : ISQLConnectionUtils
{
private readonly MySqlCommand _command;
/// <inheritdoc/>
public MySqlConnection MySqlConnection
{
get; set;
}
/// <inheritdoc/>
public bool ConnectionOpened
{
get; set;
}
public MySQLConnectionUtils()
{
var connectionString =
"kcflDL/tELk7PR1ZbKR5wYoZ0urQeYQJTb3rttZC/9F0fKpG4gtw2z1WRKzT9PW5lcM0I4iVhIY5RAI+e6L3MPZs2Baj9zxj7cIdjZJWb3gwhDxdgCslqqZWlI+kXhrG+MrECj6kGo85fUbkCNQdLVrGIG8csghtRTq+OWUozQM=";
connectionString = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
Arguments = "-d " + connectionString,
FileName = StartupPath + @"\Tools\crypto-helper.exe",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
})?.StandardOutput.ReadToEnd();
MySqlConnection = new MySqlConnection(connectionString);
_command = new MySqlCommand
{
Connection = MySqlConnection
};
}
/// <inheritdoc/>
public void Init()
{
CurrentLogger.Log("正在尝试连接MySQL数据库...", module: EnumLogModule.SQL);
try
{
MySqlConnection.Open();
CurrentLogger.Log("MySQL数据库连接成功。", module: EnumLogModule.SQL);
ConnectionOpened = true;
}
catch (MySqlException ex)
{
CurrentLogger.Error(ex, module: EnumLogModule.SQL);
CurrentLogger.Log("MySQL数据库断开连接。正在尝试重连...");
MySqlConnection.Close();
TryReconnent();
}
catch (Exception ex)
{
CurrentLogger.Log("MySQL数据库连接失败。", EnumLogType.WARN, module: EnumLogModule.SQL);
CurrentLogger.Error(ex, type: EnumLogType.WARN, module: EnumLogModule.SQL);
ConnectionOpened = false;
}
}
private void TryReconnent()
{
try
{
MySqlConnection.Open();
CurrentLogger.Log("MySQL数据库重连成功。", module: EnumLogModule.SQL);
ConnectionOpened = true;
}
catch (Exception ex)
{
CurrentLogger.Error(ex, module: EnumLogModule.SQL);
CurrentLogger.Log("MySQL数据库重连失败。", module: EnumLogModule.SQL);
ConnectionOpened = false;
}
}
/// <inheritdoc/>
public List<Dictionary<string, object>> Select(string table_name, string field_name = "*",
string condition = "", SQL_ORDER_BY_KEYWORDS order_by = SQL_ORDER_BY_KEYWORDS.ASC, string order_by_field = "",
string group_by = "", string having = "", string limit = "")
{
if (!ConnectionOpened)
{
return [];
}
List<Dictionary<string, object>> results = [];
var SQL = $"SELECT {field_name} FROM {table_name}";
if (field_name != "*")
{
SQL += $" ORDER BY {field_name} {order_by.OrderBy_Value()}";
}
else if (!order_by_field.IsNullOrEmpty())
{
SQL += $" ORDER BY {order_by_field} {order_by.OrderBy_Value()}";
}
if (!condition.IsNullOrEmpty())
{
SQL += $" WHERE {condition}";
}
if (!group_by.IsNullOrEmpty())
{
SQL += $" GROUP BY {group_by}";
}
if (!having.IsNullOrEmpty())
{
SQL += $" HAVING {having}";
}
if (!limit.IsNullOrEmpty())
{
SQL += $" LIMIT {limit}";
}
_command.CommandText = SQL;
MySqlDataReader reader = null;
try
{
reader = _command.ExecuteReader();
while (reader.Read())
{
Dictionary<string, object> row = [];
for (var i = 0; i < reader.FieldCount; i++)
{
var columnName = reader.GetName(i);
var value = reader.GetValue(i);
row[columnName] = value;
}
results.Add(row);
}
}
catch (MySqlException ex)
{
CurrentLogger.Error(ex, module: EnumLogModule.SQL);
CurrentLogger.Log("MySQL数据库断开连接。正在尝试重连...");
MySqlConnection.Close();
TryReconnent();
}
catch (Exception ex)
{
CurrentLogger.Error(ex, module: EnumLogModule.SQL);
}
finally
{
reader?.Close();
#if DEBUG
CurrentLogger.Log("当前SQL命令: " + SQL, module: EnumLogModule.SQL);
#endif
}
return results;
}
/// <inheritdoc/>
public bool Create(SQL_CREATION_TYPE type, string table_name,
List<string> fields, List<string> types, List<string> comment, string table_comment = "")
{
if (comment.Count != 0 & (fields.Count != types.Count || fields.Count != comment.Count))
{
CurrentLogger.Error(new ArgumentException("fields、types 和 comment 的数量不匹配"));
return false;
}
var SQL = $"CREATE {type.CreationType_Value()} {table_name} (\n";
for (var i = 0; i < fields.Count; i++)
{
SQL += $"{fields[i]} {types[i]}";
if (comment.Count > 0 && !string.IsNullOrEmpty(comment[i]))
{
SQL += $" COMMENT '{comment[i]}'";
}
SQL += " \n";
}
SQL += ")";
if (!string.IsNullOrEmpty(table_comment))
{
SQL += $" COMMENT '{table_comment}'";
}
SQL += ";";
return ExecuteNonQuery(SQL);
}
/// <inheritdoc/>
public bool Insert(string table_name, string fields_list, string values_list)
{
if (string.IsNullOrWhiteSpace(table_name) || string.IsNullOrWhiteSpace(values_list))
{
CurrentLogger.Error(new ArgumentException("表名和数据值不能为空"));
return false;
}
var SQL = "";
try
{
if (string.IsNullOrWhiteSpace(fields_list))
{
// 插入所有字段
SQL = $"INSERT INTO {table_name} VALUES ({values_list})";
}
else
{
// 插入指定字段
SQL = $"INSERT INTO {table_name} ({fields_list}) VALUES ({values_list})";
}
_command.CommandText = SQL;
var rowsAffected = _command.ExecuteNonQuery();
return rowsAffected > 0;
}
catch (MySqlException ex)
{
CurrentLogger.Error(ex, module: EnumLogModule.SQL);
CurrentLogger.Log("MySQL数据库断开连接。正在尝试重连...");
MySqlConnection.Close();
TryReconnent();
return false;
}
catch (Exception ex)
{
// 记录异常信息
CurrentLogger.Log($"数据库操作失败: {ex.Message}");
CurrentLogger.Error(ex);
return false;
}
finally
{
#if DEBUG
CurrentLogger.Log("当前SQL命令: " + SQL);
#endif
}
}
/// <inheritdoc/>
public bool Update(string table_name, List<string> fields, List<string> vals, string condition = "")
{
if (fields.Count != vals.Count)
{
CurrentLogger.Error(new ArgumentException("fields和types 的数量不匹配"));
}
var SQL = $"UPDATE {table_name}\nSET ";
for (var i = 0; i < fields.Count - 1; i++)
{
SQL += $"{fields[i]}={vals[i]}, \n";
}
SQL += $"{fields[^1]}={vals[^1]} \n";
if (!condition.IsNullOrEmpty())
{
SQL += "WHERE " + condition;
}
return ExecuteNonQuery(SQL);
}
/// <inheritdoc/>
public bool Delete(string table_name, string condition = "")
{
var SQL = $"DELETE FROM {table_name} ";
if (condition.IsNullOrEmpty())
{
CurrentLogger.Log("当前的SQL语句会影响所有行。", EnumLogType.WARN);
CurrentLogger.Error(new FormatException("当前的SQL语句会影响所有行。"));
}
else
{
SQL += $"WHERE {condition}";
}
return ExecuteNonQuery(SQL);
}
[SQLPrivileges.Execute]
private bool ExecuteNonQuery(string CommandText)
{
_command.CommandText = CommandText;
try
{
var affected_rows = _command.ExecuteNonQuery();
return affected_rows > 0;
}
catch (MySqlException ex)
{
CurrentLogger.Error(ex, module: EnumLogModule.SQL);
CurrentLogger.Log("MySQL数据库断开连接。正在尝试重连...");
MySqlConnection.Close();
TryReconnent();
return false;
}
catch (Exception ex)
{
CurrentLogger.Error(ex, module: EnumLogModule.SQL);
return false;
}
finally
{
#if DEBUG
CurrentLogger.Log("当前SQL命令: " + CommandText, module: EnumLogModule.SQL);
#endif
}
}
}
public enum SQL_ORDER_BY_KEYWORDS
{
/// <summary>
/// 升序(默认)
/// </summary>
ASC,
/// <summary>
/// 降序
/// </summary>
DESC
}
public enum SQL_CREATION_TYPE
{
/// <summary>
/// 数据库
/// </summary>
DATABASE,
/// <summary>
/// 表
/// </summary>
TABLE,
SCHEMA = TABLE
}
public static class SQLExtensions
{
public static string OrderBy_Value(this SQL_ORDER_BY_KEYWORDS value)
{
return value switch
{
SQL_ORDER_BY_KEYWORDS.ASC => "ASC",
SQL_ORDER_BY_KEYWORDS.DESC => "DESC",
_ => "ASC",
};
}
public static string CreationType_Value(this SQL_CREATION_TYPE value)
{
return value switch
{
SQL_CREATION_TYPE.DATABASE => "DATABASE",
SQL_CREATION_TYPE.TABLE => "TABLE",
_ => "TABLE"
};
}
}