C# DBUtility封装常见数据库操作
Yuxuan Wu Lv13

通用数据库访问类,封装了对数据库的常见操作

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.Collections.Generic;
using System.Data;
using System.Data.Common;

namespace DbHelper
{
/// <summary>
/// 通用数据库访问类,封装了对数据库的常见操作
///</summary>
public sealed class DbUtility
{
public string ConnectionString { get; set; }
private DbProviderFactory providerFactory;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="providerType">数据库类型枚举,参见<paramref name="providerType"/></param>
public DbUtility(string connectionString, DbProviderType providerType)
{
ConnectionString = connectionString;
providerFactory = ProviderFactory.GetDbProviderFactory(providerType);
if (providerFactory == null)
{
throw new ArgumentException("Can't load DbProviderFactory for given value of providerType");
}
}
/// <summary>
/// 对数据库执行增删改操作,返回受影响的行数。
/// </summary>
/// <param name="sql">要执行的增删改的SQL语句</param>
/// <param name="parameters">执行增删改语句所需要的参数</param>
/// <returns></returns>
public int ExecuteNonQuery(string sql, IList<DbParameter> parameters)
{
return ExecuteNonQuery(sql, parameters, CommandType.Text);
}
/// <summary>
/// 对数据库执行增删改操作,返回受影响的行数。
/// </summary>
/// <param name="sql">要执行的增删改的SQL语句</param>
/// <param name="parameters">执行增删改语句所需要的参数</param>
/// <param name="commandType">执行的SQL语句的类型</param>
/// <returns></returns>
public int ExecuteNonQuery(string sql, IList<DbParameter> parameters, CommandType commandType)
{
using (DbCommand command = CreateDbCommand(sql, parameters, commandType))
{
command.Connection.Open();
int affectedRows = command.ExecuteNonQuery();
command.Connection.Close();
return affectedRows;
}
}

/// <summary>
/// 执行一个查询语句,返回一个关联的DataReader实例
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数</param>
/// <returns></returns>
public DbDataReader ExecuteReader(string sql, IList<DbParameter> parameters)
{
return ExecuteReader(sql, parameters, CommandType.Text);
}

/// <summary>
/// 执行一个查询语句,返回一个关联的DataReader实例
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数</param>
/// <param name="commandType">执行的SQL语句的类型</param>
/// <returns></returns>
public DbDataReader ExecuteReader(string sql, IList<DbParameter> parameters, CommandType commandType)
{
DbCommand command = CreateDbCommand(sql, parameters, commandType);
command.Connection.Open();
return command.ExecuteReader(CommandBehavior.CloseConnection);
}

/// <summary>
/// 执行一个查询语句,返回一个包含查询结果的DataTable
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数</param>
/// <returns></returns>
public DataTable ExecuteDataTable(string sql, IList<DbParameter> parameters)
{
return ExecuteDataTable(sql, parameters, CommandType.Text);
}
/// <summary>
/// 执行一个查询语句,返回一个包含查询结果的DataTable
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数</param>
/// <param name="commandType">执行的SQL语句的类型</param>
/// <returns></returns>
public DataTable ExecuteDataTable(string sql, IList<DbParameter> parameters, CommandType commandType)
{
using (DbCommand command = CreateDbCommand(sql, parameters, commandType))
{
using (DbDataAdapter adapter = providerFactory.CreateDataAdapter())
{
adapter.SelectCommand = command;
DataTable data = new DataTable();
adapter.Fill(data);
return data;
}
}
}

/// <summary>
/// 执行一个查询语句,返回查询结果的第一行第一列
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数</param>
/// <returns></returns>
public Object ExecuteScalar(string sql, IList<DbParameter> parameters)
{
return ExecuteScalar(sql, parameters, CommandType.Text);
}

/// <summary>
/// 执行一个查询语句,返回查询结果的第一行第一列
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数</param>
/// <param name="commandType">执行的SQL语句的类型</param>
/// <returns></returns>
public Object ExecuteScalar(string sql, IList<DbParameter> parameters, CommandType commandType)
{
using (DbCommand command = CreateDbCommand(sql, parameters, commandType))
{
command.Connection.Open();
object result = command.ExecuteScalar();
command.Connection.Close();
return result;
}
}

public DbParameter CreateDbParameter(string name, object value)
{
return CreateDbParameter(name, ParameterDirection.Input, value);
}

public DbParameter CreateDbParameter(string name, ParameterDirection parameterDirection, object value)
{
DbParameter parameter = providerFactory.CreateParameter();
parameter.ParameterName = name;
parameter.Value = value;
parameter.Direction = parameterDirection;
return parameter;
}

/// <summary>
/// 创建一个DbCommand对象
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数</param>
/// <param name="commandType">执行的SQL语句的类型</param>
/// <returns></returns>
private DbCommand CreateDbCommand(string sql, IList<DbParameter> parameters, CommandType commandType)
{
DbConnection connection = providerFactory.CreateConnection();
DbCommand command = providerFactory.CreateCommand();
connection.ConnectionString = ConnectionString;
command.CommandText = sql;
command.CommandType = commandType;
command.Connection = connection;
if (!(parameters == null || parameters.Count == 0))
{
foreach (DbParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
return command;
}
}
/// <summary>
/// 数据库类型枚举
/// </summary>
public enum DbProviderType : byte
{
SqlServer,
MySql,
SQLite,
Oracle,
ODBC,
OleDb,
Firebird,
PostgreSql,
DB2,
Informix,
SqlServerCe
}
/// <summary>
/// DbProviderFactory工厂类
/// </summary>
public class ProviderFactory
{
private static Dictionary<DbProviderType, string> providerInvariantNames = new Dictionary<DbProviderType, string>();
private static Dictionary<DbProviderType, DbProviderFactory> providerFactoies = new Dictionary<DbProviderType, DbProviderFactory>(20);
static ProviderFactory()
{
//加载已知的数据库访问类的程序集
providerInvariantNames.Add(DbProviderType.SqlServer, "System.Data.SqlClient");
providerInvariantNames.Add(DbProviderType.OleDb, "System.Data.OleDb");
providerInvariantNames.Add(DbProviderType.ODBC, "System.Data.ODBC");
providerInvariantNames.Add(DbProviderType.Oracle, "Oracle.DataAccess.Client");
providerInvariantNames.Add(DbProviderType.MySql, "MySql.Data.MySqlClient");
providerInvariantNames.Add(DbProviderType.SQLite, "System.Data.SQLite");
providerInvariantNames.Add(DbProviderType.Firebird, "FirebirdSql.Data.Firebird");
providerInvariantNames.Add(DbProviderType.PostgreSql, "Npgsql");
providerInvariantNames.Add(DbProviderType.DB2, "IBM.Data.DB2.iSeries");
providerInvariantNames.Add(DbProviderType.Informix, "IBM.Data.Informix");
providerInvariantNames.Add(DbProviderType.SqlServerCe, "System.Data.SqlServerCe");
}
/// <summary>
/// 获取指定数据库类型对应的程序集名称
/// </summary>
/// <param name="providerType">数据库类型枚举</param>
/// <returns></returns>
public static string GetProviderInvariantName(DbProviderType providerType)
{
return providerInvariantNames[providerType];
}
/// <summary>
/// 获取指定类型的数据库对应的DbProviderFactory
/// </summary>
/// <param name="providerType">数据库类型枚举</param>
/// <returns></returns>
public static DbProviderFactory GetDbProviderFactory(DbProviderType providerType)
{
//如果还没有加载,则加载该DbProviderFactory
if (!providerFactoies.ContainsKey(providerType))
{
providerFactoies.Add(providerType, ImportDbProviderFactory(providerType));
}
return providerFactoies[providerType];
}
/// <summary>
/// 加载指定数据库类型的DbProviderFactory
/// </summary>
/// <param name="providerType">数据库类型枚举</param>
/// <returns></returns>
private static DbProviderFactory ImportDbProviderFactory(DbProviderType providerType)
{
string providerName = providerInvariantNames[providerType];
DbProviderFactory factory = null;
try
{
//从全局程序集中查找
factory = DbProviderFactories.GetFactory(providerName);
}
catch (ArgumentException e)
{
factory = null;
}
return factory;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//使用示例 SQLite
string connectionString = @"Data Source=D:\VS2008\NetworkTime\CrawlApplication\CrawlApplication.db3";
string sql = "SELECT * FROM Weibo_Media order by Id desc limit 0,20000";
DbUtility db = new DbUtility(connectionString, DbProviderType.SQLite);
DataTable data = db.ExecuteDataTable(sql, null);
DbDataReader reader = db.ExecuteReader(sql, null);
reader.Close();
//使用示例 MySql
string connectionString = @"Server=localhost;Database=crawldb;Uid=root;Pwd=root;Port=3306;";
string sql = "SELECT * FROM Weibo_Media order by Id desc limit 0,20000";
DbUtility db = new DbUtility(connectionString, DbProviderType.MySql);
DataTable data = db.ExecuteDataTable(sql, null);
DbDataReader reader = db.ExecuteReader(sql, null);
reader.Close();
//使用示例 Execl
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/XLS/车型.xls") + ";Extended Properties=Excel 8.0;";
string sql = "SELECT * FROM [Sheet1$]";
DbUtility db = new DbUtility(connectionString, DbProviderType.OleDb);
DataTable data = db.ExecuteDataTable(sql, null);

本文转载自:http://blog.csdn.net/smartsmile2012/article/details/8235297

  • Post title:C# DBUtility封装常见数据库操作
  • Post author:Yuxuan Wu
  • Create time:2021-05-13 02:29:10
  • Post link:yuxuanwu17.github.io2021/05/13/2021-05-13-Csharp-DBUtility封装常见数据库操作/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.