C#访问数据库SqlHelper的封装及如何访问Excel


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /www/wwwroot/fawdlstty.com/wp-content/plugins/wp-syntax/wp-syntax.php on line 383

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /www/wwwroot/fawdlstty.com/wp-content/plugins/wp-syntax/wp-syntax.php on line 383

SqlHelper这名称代表一个库,用于访问数据库的简单封装。比如一个完整的数据库查询过程:首先创建链接,然后判断链接是否有效,然后创建查询参数列表,然后调用查询语句,然后处理数据,最后关闭链接。说起来就感觉这东西有点复杂,一般有经验的程序猿都从方便自身角度对SqlHelper进行一定程度的封装,简化对数据库的调用。每个玩过数据库的程序猿都有一个,我的长这样:

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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
using System;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
 
namespace SqlHelper {
    public class sqlHelper {
        //管道连接字符串
        private static string strCon = ConfigurationManager.AppSettings["sqlstr"];
        //默认每页条数
        public const int defPageRow = 40;
 
 
 
        /// <summary>
        /// 获取Sql管道连接句柄
        /// </summary>
        /// <returns>Sql连接句柄</returns>
        private static SqlConnection GetConn () {
            SqlConnection conn = new SqlConnection (strCon);
            conn.Open ();
            return conn;
        }
 
 
 
        /// <summary>
        /// 关闭Sql管道连接
        /// </summary>
        /// <param name="conn">管道连接句柄</param>
        private static void Close (SqlConnection conn) {
            try {
                if (conn == null) return;
                if (conn.State == ConnectionState.Open) conn.Close ();
                conn.Dispose ();
            } catch (Exception) { }
        }
 
 
 
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="oc"></param>
        /// <returns></returns>
        public static SqlParameter[] GetParameter (params object[] oc) {
            if (oc == null || oc.Length == 0) {
                return null;
            } else if (oc.Length % 2 > 0) {
                throw new Exception ("参数个数不可为奇数!");
            }
            int count = oc.Length / 2;
            SqlParameter[] spc = new SqlParameter[count];
            for (int i = 0; i < count; i++) {
                if (oc[i * 2].ToString ()[0] != '@') throw new Exception ("参数名命名规则错误!");
                spc[i] = new SqlParameter ();
                spc[i].ParameterName = oc[i * 2].ToString ();
                spc[i].Value = oc[i * 2 + 1];
            }
            return spc;
        }
 
 
 
        /// <summary>
        /// 拷贝数据库参数
        /// </summary>
        /// <param name="spc">数据库参数</param>
        /// <returns>数据库参数</returns>
        private static SqlParameter[] GetNewSqlParameterCollection (SqlParameter[] spc) {
            if (spc == null) return null;
            SqlParameter[] ret = new SqlParameter[spc.Length];
            for (int i = 0; i < spc.Length; i++) {
                ret[i] = new SqlParameter ();
                ret[i].ParameterName = spc[i].ParameterName;
                ret[i].Value = spc[i].Value;
            }
            return ret;
        }
 
 
 
        /// <summary>
        /// ExecuteNonQuery你懂得
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>受影响行数</returns>
        public static int ExecuteNonQuery (string sqlstr, SqlParameter[] spc) {
            SqlConnection conn = GetConn ();
            SqlCommand cmd = new SqlCommand (sqlstr, conn);
            SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
            if (spc2 != null) cmd.Parameters.AddRange (spc2);
            int ret = cmd.ExecuteNonQuery ();
            Close (conn);
            return ret;
        }
 
 
 
        /// <summary>
        /// ExecuteNonQuery你懂得
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="oc">字符串参数数组</param>
        /// <returns>受影响行数</returns>
        public static int ExecuteNonQuery (string sqlstr, params object[] oc) {
            return ExecuteNonQuery (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// ExecuteScalary你懂得
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>返回的结果</returns>
        public static object ExecuteScalary (string sqlstr, SqlParameter[] spc) {
            SqlConnection conn = GetConn ();
            SqlCommand cmd = new SqlCommand (sqlstr, conn);
            SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
            if (spc2 != null) cmd.Parameters.AddRange (spc2);
            object ret = cmd.ExecuteScalar ();
            Close (conn);
            return ret;
        }
 
 
 
        /// <summary>
        /// ExecuteScalary你懂得
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="oc">字符串参数数组</param>
        /// <returns>返回的结果</returns>
        public static object ExecuteScalary (string sqlstr, params object[] oc) {
            return ExecuteScalary (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// ExecuteDataTable你懂得
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>返回的表格</returns>
        public static DataTable ExecuteDataTable (string sqlstr, SqlParameter[] spc) {
            SqlConnection conn = GetConn ();
            SqlCommand cmd = new SqlCommand (sqlstr, conn);
            SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
            if (spc2 != null) cmd.Parameters.AddRange (spc2);
            DataSet ds = new DataSet ();
            SqlDataAdapter sda = new SqlDataAdapter (cmd);
            sda.Fill (ds);
            DataTable ret = ds.Tables[0];
            Close (conn);
            return ret;
        }
 
 
 
        /// <summary>
        /// ExecuteDataTable你懂得
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="oc">字符串参数数组</param>
        /// <returns>返回的表格</returns>
        public static DataTable ExecuteDataTable (string sqlstr, object[] oc) {
            return ExecuteDataTable (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// ExecuteDataSet你懂得
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="spc"></param>
        /// <returns></returns>
        public static DataSet ExecuteDataSet (string sqlstr, SqlParameter[] spc) {
            DataSet ds = new DataSet ();
            SqlConnection conn = GetConn ();
            SqlCommand cmd = new SqlCommand (sqlstr, conn);
            SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
            if (spc2 != null) cmd.Parameters.AddRange (spc2);
            SqlDataAdapter sda = new SqlDataAdapter (cmd);
            sda.Fill (ds);
            Close (conn);
            return ds;
        }
 
 
 
        /// <summary>
        /// ExecuteDataSet你懂得
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="oc">字符串参数数组</param>
        /// <returns>返回的表格</returns>
        public static DataSet ExecuteDataSet (string sqlstr, object[] oc) {
            return ExecuteDataSet (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// 获取某表行数
        /// </summary>
        /// <param name="table">表名(可附加条件)</param>
        /// <param name="spc">参数</param>
        /// <returns>行数</returns>
        public static int GetCount (string table, SqlParameter[] spc = null) {
            return sqlHelper2.ExecuteScalary (string.Format ("select count(*) from {0}", table), spc).toInt32 ();
        }
 
 
 
        /// <summary>
        /// 获取多张表函数总和
        /// </summary>
        /// <param name="spc">参数</param>
        /// <param name="table">表名(可附加条件)</param>
        /// <returns>行数</returns>
        public static int GetCountTotal (SqlParameter[] spc, params string[] table) {
            return sqlHelper2.ExecuteScalary(string.Format("select (select count(*) from {0})", table.join(") + (select count(*) from ")), spc).toInt32();
        }
 
 
 
        /// <summary>
        /// 获取某表查询时的页数
        /// </summary>
        /// <param name="table">表名</param>
        /// <param name="pageRow">每页行数</param>
        /// <returns></returns>
        public static int GetPageCount (string table, SqlParameter[] spc = null, int pageRow = sqlHelper2.defPageRow) {
            try {
                int count = GetCount (table, spc);
                return count / pageRow + (count % pageRow > 0 ? 1 : 0);
            } catch (Exception) {
                return 1;
            }
        }
 
 
 
        /// <summary>
        /// 检查页码是否正确
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="count">每页条数</param>
        /// <returns>正确的页码</returns>
        public static int CheckPage (int page, int count) {
            if (page < 1)
                return 1;
            else if (page > count)
                return count;
            else
                return page;
        }
 
 
 
        /// <summary>
        /// 获取新ID
        /// </summary>
        /// <returns></returns>
        public static string GetNewID () {
            //return sqlHelper2.ExecuteScalary ("select newid()", null).ToString ();
            return Guid.NewGuid ().toString ();
        }
 
 
 
        /// <summary>
        /// 获取某列表
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>列表数组</returns>
        public static string[] sGlobalGetList (string sqlstr, SqlParameter[] spc) {
            DataTable dt = sqlHelper2.ExecuteDataTable (sqlstr, spc);
            if (dt.Rows.Count == 0) return null;
            string[] sc = new string[dt.Rows.Count];
            StringBuilder sb;
            for (int i = 0; i < dt.Rows.Count; i++) {
                sb = new StringBuilder ();
                for (int j = 0; j < dt.Columns.Count; j++) {
                    if (j != 0)
                        sb.Append ("#");
                    //sb.Append(dt.Rows[i][j].ToString());
                    try {
                        if (dt.Columns[j].DataType.ToString ().Trim () == "DateTime") {
                            sb.Append (Convert.ToDateTime (dt.Rows[i][j]).ToString ("yyyy-MM-dd"));
                        } else {
                            sb.Append (dt.Rows[i][j].ToString ().Trim ());
                        }
                    } catch (Exception) { }
                }
                sc[i] = sb.ToString ();
            }
            return sc;
        }
 
 
 
        /// <summary>
        /// 获取某列表
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="oc">字符串参数数组</param>
        /// <returns>列表数组</returns>
        public static string[] sGlobalGetList (string sqlstr, params object[] oc) {
            return sGlobalGetList (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// 获取某列表(完整时间)
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>列表数组</returns>
        public static string[] sGlobalGetListLongTime (string sqlstr, SqlParameter[] spc) {
            DataTable dt = sqlHelper2.ExecuteDataTable (sqlstr, spc);
            if (dt.Rows.Count == 0)
                return null;
            string[] sc = new string[dt.Rows.Count];
            StringBuilder sb;
            for (int i = 0; i < dt.Rows.Count; i++) {
                sb = new StringBuilder ();
                for (int j = 0; j < dt.Columns.Count; j++) {
                    if (j != 0)
                        sb.Append ("#");
                    //sb.Append(dt.Rows[i][j].ToString());
                    try {
                        if (dt.Columns[j].DataType.ToString ().Trim () == "DateTime") {
                            sb.Append (Convert.ToDateTime (dt.Rows[i][j]).ToString ("yyyy-MM-dd HH:mm"));
                        } else {
                            sb.Append (dt.Rows[i][j].ToString ().Trim ());
                        }
                    } catch (Exception) { }
                }
                sc[i] = sb.ToString ();
            }
            return sc;
        }
 
 
 
        /// <summary>
        /// 获取某列表(完整时间)
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>列表数组</returns>
        public static string[] sGlobalGetListLongTime (string sqlstr, params object[] oc) {
            return sGlobalGetListLongTime (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// 获取某行数据
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>行数组</returns>
        public static string[] sGlobalGetLine (string sqlstr, SqlParameter[] spc) {
            DataTable dt = sqlHelper2.ExecuteDataTable (sqlstr, spc);
            if (dt.Rows.Count == 0) return null;
            string[] sc = new string[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++) {
                try {
                    if (dt.Columns[i].DataType.ToString ().IndexOf ("DateTime") >= 0) {
                        sc[i] = dt.Rows[0][i].toDateTime ().formatDate ();
                    } else {
                        sc[i] = dt.Rows[0][i].toString ();
                    }
                } catch (Exception) {
                    sc[i] = "";
                }
            }
            return sc;
        }
 
 
 
        /// <summary>
        /// 获取某行数据
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>行数组</returns>
        public static string[] sGlobalGetLine (string sqlstr, params object[] oc) {
            return sGlobalGetLine (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// 获取某行数据(完整时间)
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>行数组</returns>
        public static string[] sGlobalGetLineLongTime (string sqlstr, SqlParameter[] spc) {
            DataTable dt = sqlHelper2.ExecuteDataTable (sqlstr, spc);
            if (dt.Rows.Count == 0)
                return null;
            string[] sc = new string[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++) {
                try {
                    if (dt.Columns[i].DataType.ToString ().IndexOf ("DateTime") >= 0) {
                        sc[i] = dt.Rows[0][i].toDateTime ().formatDateTime ();
                    } else {
                        sc[i] = dt.Rows[0][i].toString ();
                    }
                } catch (Exception) {
                    sc[i] = "";
                }
            }
            return sc;
        }
 
 
 
        /// <summary>
        /// 获取某行数据(完整时间)
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>行数组</returns>
        public static string[] sGlobalGetLineLongTime (string sqlstr, params object[] oc) {
            return sGlobalGetLineLongTime (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// 获取完整某表
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>二维列表数组</returns>
        public static string[][] mGlobalGetList (string sqlstr, SqlParameter[] spc) {
            DataTable dt = sqlHelper2.ExecuteDataTable (sqlstr, spc);
            string[][] s = new string[dt.Rows.Count][];
            for (int i = 0; i < dt.Rows.Count; i++) {
                s[i] = new string[dt.Columns.Count];
                for (int j = 0; j < dt.Columns.Count; j++) {
                    string t = dt.Columns[j].DataType.ToString ().Trim ();
                    if (t.IndexOf ('.') >= 0) {
                        t = t.Substring (t.LastIndexOf ('.') + 1);
                    }
                    try {
                        if (t == "DateTime") {
                            s[i][j] = Convert.ToDateTime (dt.Rows[i][j]).ToString ("yyyy-MM-dd");
                        } else {
                            s[i][j] = dt.Rows[i][j].ToString ().Trim ();
                        }
                    } catch (Exception) {
                        s[i][j] = "";
                    }
                }
            }
            return s;
        }
 
 
 
        /// <summary>
        /// 获取完整某表
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>二维列表数组</returns>
        public static string[][] mGlobalGetList (string sqlstr, params object[] oc) {
            return mGlobalGetList (sqlstr, GetParameter (oc));
        }
 
 
 
        /// <summary>
        /// 获取完整某表(完整时间)
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="spc">数据库参数</param>
        /// <returns>二维列表数组</returns>
        public static string[][] mGlobalGetListLongTime (string sqlstr, SqlParameter[] spc) {
            DataTable dt = sqlHelper2.ExecuteDataTable (sqlstr, spc);
            string[][] s = new string[dt.Rows.Count][];
            for (int i = 0; i < dt.Rows.Count; i++) {
                s[i] = new string[dt.Columns.Count];
                for (int j = 0; j < dt.Columns.Count; j++) {
                    string t = dt.Columns[j].DataType.ToString ().Trim ();
                    if (t.IndexOf ('.') >= 0) {
                        t = t.Substring (t.LastIndexOf ('.') + 1);
                    }
                    try {
                        if (t == "DateTime") {
                            s[i][j] = Convert.ToDateTime (dt.Rows[i][j]).formatDateTime ();
                        } else {
                            s[i][j] = dt.Rows[i][j].ToString ().Trim ();
                        }
                    } catch (Exception) {
                        s[i][j] = "";
                    }
                }
            }
            return s;
        }
 
 
 
        /// <summary>
        /// 获取完整某表(完整时间)
        /// </summary>
        /// <param name="sqlstr">数据库语句</param>
        /// <param name="oc">字符串参数数组</param>
        /// <returns>二维列表数组</returns>
        public static string[][] mGlobalGetListLongTime (string sqlstr, params object[] oc) {
            return mGlobalGetListLongTime (sqlstr, GetParameter (oc));
        }
    }
}

注:使用方法不细说,这东西还有个好处是可以直接通过Sql语句来访问Excel表格,具体方法为,改引用 System.Data.SqlClient 为 System.Data.OleDb,然后会提示一堆错,找不到类型之类的,全局替换错误的名称,比如 SqlConnection 全局替换为 OleDbConnection等等,替换完成后传入的链接字符串格式为:

Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=D:/a.xls

然后就可以通过数据库语句来访问Excel了。

发布者

fawdlstty

又一只萌萌哒程序猿~~

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注