public static class DbConnector private static readonly MySqlConnectio

 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
public static class DbConnector
{
private static readonly MySqlConnection Connection;
static DbConnector()
{
var connectionString = new MySqlConnectionStringBuilder()
{
Server = "127.0.0.1",
Database = "doghouse",
UserID = "root",
Password =
};
var con = new MySqlConnection(connectionString.ConnectionString);
try
{
con.Open();
}
catch
{
System.Windows.Forms.MessageBox.Show("Невозможно подключиться к базе данных.");
Environment.Exit(0);
}
con.Close();
Connection = con;
}
public static DataTable GetTable(string tableName)
{
return ExecuteSelect($"SELECT * FROM {tableName}");
}
/// <summary>
/// Select
/// </summary>
public static DataTable ExecuteSelect(string query)
{
Connection.Open();
var dt = new DataTable();
using(var cmd = new MySqlCommand(query, Connection))
{
using(var reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
dt.Load(reader);
}
}
}
Connection.Close();
return dt;
}
/// <summary>
/// Insert, Update, Delete
/// </summary>
public static long ExecuteNonQuery(string query)
{
Connection.Open();
using(var cmd = new MySqlCommand(query, Connection))
{
cmd.ExecuteNonQuery();
Connection.Close();
return cmd.LastInsertedId;
}
}
}