본문 바로가기
IT/Programming

C# MySQL Helper Class

by 여우요원 2018. 7. 26.



C# 에서 사용할 수 있는 MySQL Helper Class

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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
using System;
using System.Data;
using MySql.Data.MySqlClient;
 
namespace Sentbe.Database
{
    public class MySqlHelper : IDisposable
    {
        private MySqlConnection connection = null;
        private String connectionString = "dbConnection";
        private MySqlDataAdapter sqlData = new MySqlDataAdapter();
        public MySqlCommand sqlCmd = new MySqlCommand();
 
        // {0} : IP, {1} : Port, {2} : DB Name, {3} : userID, {4} : userPW
        private String connectionFormat = "Server={0};Database={1};Uid={2};Pwd={3};";
 
        public String ConnectionString
        {
            set { connectionString = value; }
        }
 
        #region Constructors
 
        public MySqlHelper()
        {
            connectionString = AppConfigHelper.getConnectionString("conn");
        }
 
        public MySqlHelper(string pConnectionString)
        {
            if (!string.IsNullOrEmpty(pConnectionString.Trim()))
            {
                connectionString = pConnectionString;
            }
        }
 
        public MySqlHelper(string pIP, string pDbName, string pUserID, string pUserPW)
        {
            connectionString = string.Format(this.connectionFormat, pIP, pDbName, pUserID, pUserPW);
 
        }
        #endregion
 
 
        /// <summary>
        /// Sql Script / Stored Procedure Name
        /// </summary>
        public string CmdText
        {
            set { sqlCmd.CommandText = value; }
        }
 
        /// <summary>
        /// CommandType = CommandType....
        /// </summary>
        public CommandType cmdType
        {
 
            set { sqlCmd.CommandType = value; }
        }
 
        /// <summary>
        /// AddParameter(iSql, "return_value", SqlDbType.Int , "", ParameterDirection.ReturnValue , 5); ---- return문
        /// AddParameter(iSql, "@MSG_TEXT", SqlDbType.VarChar, "", ParameterDirection.Output, 100);
        /// </summary>
        /// <param name="Param"></param>
        /// <param name="Db_Type"></param>
        /// <param name="values"></param>
        /// <param name="Param_io"></param>
        /// <param name="nSize"></param>
        public void AddParameter(string Param, MySqlDbType Db_Type, object values, ParameterDirection Param_io, int nSize)
        {
            MySqlParameter param1 = new MySqlParameter(Param, Db_Type);
            if (Param_io == ParameterDirection.Input || Param_io == ParameterDirection.InputOutput)
                param1.Value = values;
            param1.Direction = Param_io;
            param1.Size = nSize;
            sqlCmd.Parameters.Add(param1);
        }
 
 
        #region Add Parameter TO Query
 
        private void AddParameter(MySqlCommand command, string parameterName, MySqlDbType dbType, int size, ParameterDirection direction, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
        {
            MySqlParameter p = new MySqlParameter(parameterName, dbType, size, direction, true, precision, scale, sourceColumn, sourceVersion, value);
            command.Parameters.Add(p);
        }
 
        public void AddParameter(MySqlCommand command, string parameterName, MySqlDbType dbType, int size, ParameterDirection direction, object value)
        {
            AddParameter(command, parameterName, dbType, size, direction, 00null, DataRowVersion.Current, value);
        }
 
        public void AddInParameter(MySqlCommand command, string parameterName, MySqlDbType dbType, object value)
        {
            AddParameter(command, parameterName, dbType, 0, ParameterDirection.Input, value);
        }
 
        public void AddOutParameter(MySqlCommand command, string parameterName, MySqlDbType dbType, int size)
        {
            AddParameter(command, parameterName, dbType, size, ParameterDirection.Output, null);
        }
 
        /// <summary>
        /// Store_Param(iSql, "@prc", SqlDbType.VarChar,"C");
        /// </summary>
        /// <param name="Param"></param>
        /// <param name="Db_Type"></param>
        /// <param name="values"></param>
        public void AddParameter(string Param, MySqlDbType Db_Type, object values)
        {
            MySqlParameter param1 = new MySqlParameter(Param, Db_Type);
            param1.Value = values;
            sqlCmd.Parameters.Add(param1);
        }
 
        /// <summary>
        /// Store_Param(iSql, "@MSG_CD", SqlDbType.VarChar, "", ParameterDirection.Output);
        /// </summary>
        /// <param name="Param"></param>
        /// <param name="Db_Type"></param>
        /// <param name="values"></param>
        /// <param name="Param_io"></param>
        public void AddParameter(string Param, MySqlDbType Db_Type, object values, ParameterDirection Param_io)
        {
            MySqlParameter param1 = new MySqlParameter(Param, Db_Type);
            if (Param_io == ParameterDirection.Input || Param_io == ParameterDirection.InputOutput)
                param1.Value = values;
            param1.Direction = Param_io;
            sqlCmd.Parameters.Add(param1);
        }
 
        public object GetParameterValue(MySqlCommand command, string parameterName)
        {
            return command.Parameters[parameterName].Value;
        }
 
        /// <summary>
        /// sp의 OUTPUT 파라미터 값 읽기
        /// int(string) return = (int/string)Return_Param("@return");
        /// </summary>
        /// <param name="param">"@param"</param>
        /// <returns>object</returns>
        public object GetParameter(string param)
        {
            return sqlCmd.Parameters[param].Value;
        }
        #endregion
 
        #region Generating SqlCommand
 
        private MySqlCommand PrepareCommand(CommandType commandType, string commandText)
        {
            if (connection == null)
            {
                connection = new MySqlConnection(this.connectionString);
            }
            if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken)
            {
                connection.Open();
            }
            MySqlCommand command = new MySqlCommand(commandText, connection);
            command.CommandType = commandType;
            return command;
        }
 
        public MySqlCommand GetStoreProcedureCommand(string spname)
        {
            return PrepareCommand(CommandType.StoredProcedure, spname);
        }
 
        public MySqlCommand GetSqlQueryCommand(string query)
        {
            return PrepareCommand(CommandType.Text, query);
        }
        #endregion
 
        #region Direct Quer
 
        public int DirectNonQuery(string query)
        {
            MySqlCommand sc = GetSqlQueryCommand(query);
            int iResult = ExecuteNonQuery(sc);
            return iResult;
        }
 
        /// <summary>
        /// 직접 쿼리결과를 가져오는 함수
        /// </summary>
        /// <param name="sQuery"></param>
        /// <returns></returns>
        public DataTable stringQuery(string sQuery)
        {
            return new MySqlHelper().DirectQuery(sQuery);
        }
 
        public DataTable DirectQuery(string query)
        {
            MySqlCommand sc = GetSqlQueryCommand(query);
            return LoadDataTable(sc, string.Empty);
        }
 
        public DataTable DirectQuery(string query, string tableName)
        {
            MySqlCommand sc = GetSqlQueryCommand(query);
            return LoadDataTable(sc, string.Empty);
        }
 
        /// <summary>
        /// 쿼리명령어(Update/Insert/Delete)등 실행
        /// </summary>
        /// <param name="sQuery"></param>
        /// <returns>Return 1(Success) / 0(Fail)</returns>
        public int StringNonQuery(string sQuery)
        {
            return new MySqlHelper().DirectNonQuery(sQuery);
        }
        #endregion
 
        #region Database Related Command
 
        public int ExecuteNonQuery(MySqlCommand command)
        {
            return command.ExecuteNonQuery();
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public int ExcuteNonQuery()
        {
            return sqlExcuteNonQuery(0);
        }
 
        /// <summary>
        /// Sql Excute Command
        /// Transaction: 1 begin transaction
        /// Transaction: 0 No transaction
        /// </summary>
        /// <param name="Transaction">Transaction= 1 Or 0</param>
        /// <returns>Return Effective Rows</returns>
        public int sqlExcuteNonQuery(int Transaction)
        {
            try
            {
                sqlData.SelectCommand = sqlCmd;
                sqlCmd.Connection = new MySqlConnection(this.connectionString);
                sqlCmd.Connection.Open();
                if (Transaction > 0)
                    sqlCmd.Transaction = sqlCmd.Connection.BeginTransaction(IsolationLevel.ReadCommitted);
 
                int rtn = sqlCmd.ExecuteNonQuery();
 
                if (Transaction > 0)
                    sqlCmd.Transaction.Commit();
                sqlCmd.Connection.Close();
 
                return rtn;
            }
            catch
            {
                if (Transaction > 0)
                    sqlCmd.Transaction.Rollback();
 
                return -1;
            }
            finally
            {
            }
        }
 
        public object ExecuteScalar(MySqlCommand command)
        {
            return command.ExecuteScalar();
        }
 
        public MySqlDataReader ExecuteReader(MySqlCommand command)
        {
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }
 
        public MySqlDataReader ExecuteReader(MySqlCommand command, CommandBehavior commandBehavior)
        {
            return command.ExecuteReader(commandBehavior);
        }
 
        public DataTable LoadDataTable(MySqlCommand command, string tableName)
        {
            using (MySqlDataAdapter da = new MySqlDataAdapter(command))
            {
                using (DataTable dt = new DataTable(tableName))
                {
                    da.Fill(dt);
                    return dt;
                }
            }
        }
 
        public DataSet LoadDataSet(MySqlCommand command, string[] tableNames)
        {
            using (MySqlDataAdapter da = new MySqlDataAdapter(command))
            {
                using (DataSet ds = new DataSet())
                {
                    da.Fill(ds);
                    if (tableNames != null)
                    {
                        for (int i = 0; i < ds.Tables.Count; i++)
                        {
                            try
                            {
                                ds.Tables[i].TableName = tableNames[i];
                            }
                            catch
                            {
                            }
                        }
                    }
 
                    return ds;
                }
            }
        }
 
        /// <summary>
        /// DataSet 요청
        /// </summary>
        /// <returns>DataSet</returns>
        public DataSet LoadDataSet()
        {
            //
            DataSet ds = new DataSet();
            try
            {
                sqlData.SelectCommand = sqlCmd;
                sqlCmd.Connection = new MySqlConnection(this.connectionString);
 
                sqlData.Fill(ds);
 
                return ds;
            }
            catch
            {
                return null;
            }
            finally
            {
            }
        }
 
        private MySqlTransaction PrepareTransaction(IsolationLevel isolationLevel)
        {
            if (connection == null)
            {
                connection = new MySqlConnection(this.connectionString);
            }
            if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken)
            {
                connection.Open();
            }
            return connection.BeginTransaction(isolationLevel);
        }
 
        public MySqlTransaction BeginTransaction()
        {
            return PrepareTransaction(IsolationLevel.ReadCommitted);
        }
 
        public MySqlTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            return PrepareTransaction(isolationLevel);
        }
 
        public void Commit(MySqlTransaction transaction)
        {
            if (transaction != null)
                transaction.Commit();
        }
 
        public void RollBack(MySqlTransaction transaction)
        {
            if (transaction != null)
                transaction.Rollback();
        }
        #endregion
 
        #region IDisposable Members
 
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
        #endregion
 
        #region Destructor
 
        ~MySqlHelper()
        {
            Dispose();
        }
        #endregion
 
        void IDisposable.Dispose()
        {
            if (connection != null)
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    connection.Dispose();
                }
            }
        }
 
    }   // end of class
 
}   // end of namespace
 
cs


'IT > Programming' 카테고리의 다른 글

Convert MySQL data To Json in PHP  (0) 2019.03.28
C# Postgresql Helper Class  (0) 2019.03.21
C#에서 SSH로 원격(Remote)에 있는 MySql 접속하기  (0) 2018.07.26
C# SqlHelper Class  (0) 2016.05.27
ExtraGrid 컬럼 Merge하기  (0) 2016.02.03