-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBConnection.cs
264 lines (241 loc) · 11.6 KB
/
DBConnection.cs
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
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace BTL
{
/// <summary>
/// Lớp dùng chung cho việc sử lý đến DataBase
/// </summary>
public class DBConnection
{
/// <summary>
/// Làm cho màu mè chuẩn tính đóng gói của OOP =)))
/// <br/>
/// Là <see cref="System.Data.DataSet"/> chứa các dữ liệu của <see cref="DataTable"/> khi sử dụng các hàm select, update, ...
/// </summary>
public DataSet DataSet => _dataSet;
/// <summary>
/// Làm cho màu mè chuẩn tính đóng gói của OOP =)))
/// <br/>
/// Là 1 thể hiện hay là gì đấy =)) k biết dịch là gì
/// <br/>
/// Chủ yếu là để sử dụng các hàm của lớp không cần phải tạo ra đối tượng mới từ lớp
/// </summary>
public static DBConnection Instance => _instance;
/// <summary>
/// Làm cho màu mè chuẩn tính đóng gói của OOP =)))
/// </summary>
private static DBConnection _instance = new DBConnection();
/// <summary>
/// Làm cho màu mè chuẩn tính đóng gói của OOP =)))
/// </summary>
private DataSet _dataSet = new DataSet();
/// <summary>
/// Hàm tạo <see cref="SqlConnection"/> từ <see cref="ConfigurationManager"/> ConnectionString "dbConnection"
/// </summary>
/// <returns><see cref="SqlConnection"/></returns>
public SqlConnection CreateConnection()
{
string constr = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
return new SqlConnection(constr);
}
/// <summary>
/// Hàm tạo <see cref="SqlParameter"/> đầy đủ để chuẩn theo các hàm sử lý như insert, update
/// </summary>
/// <param name="parameterName">Tên tham số, thường bắt đàu bằng @ VD: @sHoTen</param>
/// <param name="dbType">Loại thuộc tính VD: <see cref="SqlDbType.NChar"/> là nvarchar trong database,<see cref="SqlDbType.bit"/> là bit trong database, ... </param>
/// <param name="size">Kích thước của dữ liệu</param>
/// <param name="sourceColumn">Tên cột trong DataBase VD: sHoTen</param>
/// <param name="value">Giá trị cho cột</param>
/// <returns><see cref="SqlParameter"/></returns>
public SqlParameter BuildParameter(string parameterName, SqlDbType dbType, int size, string sourceColumn, object value)
{
return new SqlParameter(parameterName, dbType, size, sourceColumn) { Value = value };
}
/// <summary>
/// Hàm lấy dữ liệu từ DataBase
/// <br/>
/// Nó sẽ tự cập nhật thêm vào <see cref="DataSet"/> nên tất cả mọi thứ binding đến sẽ update theo
/// </summary>
/// <param name="table">Tên bảng</param>
/// <param name="query">(Nếu có) Mã SQL sau WHERE VD: "bDeleted=0 AND sHoTen LIKE %N%"</param>
/// <returns>Dữ liệu của bảng dạng DataTable</returns>
public DataTable SelectDB(string table, string query = "")
{
using (SqlConnection cnn = CreateConnection())
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
using (SqlCommand cmd = cnn.BuildSelectCommand(table, query))
{
try
{
da.SelectCommand = cmd;
_dataSet.Tables[table]?.Clear();
cnn.Open();
da.Fill(_dataSet, table);
cnn.Close();
}
catch (Exception ex)
{
throw new Exception("Lỗi select DataBase : " + ex.Message);
}
}
}
}
return _dataSet.Tables[table];
}
/// <summary>
/// Hàm thêm dữ liệu bằng Command vào DataBase
/// <br/>
/// Nó sẽ tự cập nhật thêm vào <see cref="DataSet"/> nên tất cả mọi thứ binding đến sẽ update theo
/// </summary>
/// <param name="table">Tên bảng</param>
/// <param name="sqlParameters">Các thuộc tính cần thêm vào bảng (sử dụng <see cref="BuildParameter"/> để tạo ra parameter cho chuẩn dạng dữ liệu)</param>
/// <returns><c>True</c> Nếu thêm thành công, ngược lại <c>False</c></returns>
public bool InsertDB(string table, params SqlParameter[] sqlParameters)
{
using (SqlConnection cnn = CreateConnection())
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
using (SqlCommand cmd = cnn.BuildInsertCommand(table, sqlParameters))
{
try
{
da.InsertCommand = cmd;
DataRow newRow = _dataSet.Tables[table].NewRow();
foreach (var p in sqlParameters)
{
newRow[p.SourceColumn] = p.Value;
}
_dataSet.Tables[table].Rows.Add(newRow);
cnn.Open();
int i = da.Update(_dataSet, table);
cnn.Close();
return i > 0;
}
catch (Exception ex)
{
throw new Exception("Lỗi insert DataBase : " + ex.Message);
}
}
}
}
}
/// <summary>
/// Hàm thêm dữ liệu bằng Proc vào DataBase
/// <br/>
/// Nó sẽ tự cập nhật thêm vào <see cref="DataSet"/> nên tất cả mọi thứ binding đến sẽ update theo
/// </summary>
/// <param name="table">Tên bảng</param>
/// <param name="nameProc">Tên hàm sử dụng trong để thêm dữ liệu</param>
/// <param name="sqlParameters">Các thuộc tính cần thêm vào bảng (sử dụng <see cref="BuildParameter)"/> để tạo ra parameter cho chuẩn dạng dữ liệu)</param>
/// <returns><c>True</c> Nếu thêm thành công, ngược lại <c>False</c></returns>
public bool InsertDB(string table, string nameProc, params SqlParameter[] sqlParameters)
{
if (_dataSet.Tables[table] == null) SelectDB(table);
using (SqlConnection cnn = CreateConnection())
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
using (SqlCommand cmd = cnn.BuildInsertProc(nameProc, sqlParameters))
{
try
{
da.InsertCommand = cmd;
DataRow newRow = _dataSet.Tables[table].NewRow();
foreach (var p in sqlParameters)
{
newRow[p.SourceColumn] = p.Value;
}
_dataSet.Tables[table].Rows.Add(newRow);
cnn.Open();
int i = da.Update(_dataSet, table);
cnn.Close();
return i > 0;
}
catch (Exception ex)
{
throw new Exception("Lỗi insert DataBase : " + ex.Message);
}
}
}
}
}
/// <summary>
/// Hàm lấy dữ liệu của 1 bản ghi bất khì nào trong bảng
/// </summary>
/// <param name="table">Tên bảng</param>
/// <param name="sourceColumn">Tên cột để kiểm tra lấy ra bản ghi (Nên sử dụng ID)</param>
/// <param name="value">Giá trị của cột để kiểm tra lấy ra bản ghi (Nên sử dụng ID)</param>
/// <returns><c><see cref="DataRow"/></c>Nếu thì thấy bản ghi phù hợp với <paramref name="value"/>, ngược lại <see cref="null"/></returns>
public DataRow GetRow(string table, string sourceColumn, object value)
{
if (_dataSet.Tables[table] == null) SelectDB(table);
foreach (DataRow row in _dataSet.Tables[table].Rows)
{
if (row[sourceColumn].ToString().Equals(value.ToString()))
return row;
}
return null;
}
/// <summary>
/// Hàm cập nhật dữ liệu bằng Command vào DataBase
/// <br/>
/// Nó sẽ tự cập nhật thêm vào <see cref="DataSet"/> nên tất cả mọi thứ binding đến sẽ update theo
/// </summary>
/// <param name="table">Tên bảng</param>
/// <param name="condition">Tên điều kiện cập nhật (sử dụng <see cref="BuildParameter)"/> để tạo ra parameter cho chuẩn dạng dữ liệu)</param>
/// <param name="sqlParameters">Các thuộc tính cần cập nhật vào bảng (sử dụng <see cref="BuildParameter)"/> để tạo ra parameter cho chuẩn dạng dữ liệu)</param>
/// <returns><c>True</c> Nếu cập nhật thành công, ngược lại <c>False</c></returns>
public bool UpdateDB(string table, SqlParameter condition, params SqlParameter[] sqlParameters)
{
DataTable dt = _dataSet.Tables[table];
if (_dataSet.Tables[table] == null)
{
dt = SelectDB(table);
}
using (SqlConnection cnn = CreateConnection())
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
using (SqlCommand cmd = cnn.BuildUpdateCommand(table, condition, sqlParameters))
{
try
{
da.UpdateCommand = cmd;
cnn.Open();
var row = GetRow(table, condition.SourceColumn, condition.Value);
foreach (var p in sqlParameters)
{
row[p.SourceColumn] = p.Value;
}
int i = da.Update(_dataSet, table);
cnn.Close();
return i > 0;
}
catch (Exception ex)
{
throw new Exception("Lỗi update DataBase : " + ex.Message);
}
}
}
}
}
/// <summary>
/// Hàm xóa dữ liệu
/// </summary>
/// <param name="table">Tên bảng cần xóa</param>
/// <param name="condition">Tên điều kiện để xóa thường là sử dụng ID (sử dụng <see cref="BuildParameter)"/> để tạo ra parameter cho chuẩn dạng dữ liệu)</param>
/// <returns></returns>
public bool DeleteDB(string table, SqlParameter condition)
{
return UpdateDB(table,
condition,
BuildParameter("@bDeleted", SqlDbType.Bit, 0, "bDeleted", true));
}
}
}