数据库连接NET 应用程序配置方法(学习笔记)
无论在桌面应用项目还是在Web项目下,经常会遇到一些可能是随着需求或其他原因更变而更变的功能,遇到这样的情况有可能导致需要重新更改程序和重新部署,例如在某项目中我们使用 Sql Server 作为数据来源并为其编写访问数据的程序,当某天需要使用 Access 作为数据来源时,可能整个项目的那些关于数据访问的代码都需要重写。在理想的情况下,我们希望到底使用 Sql Server 还是 Access 作为数据来源是由外部决定的,并且它是方便修改并且不必重新编译已部署好的程序。在三层构架开发模式下,可以将数据库的数据访问代码分别编写在自己的DLL中,使用应用程序配置来作为一个外部的“切换开关”,例如,原来是使用 Sql Server 数据访问的DLL时,设想在配置文件中设置一个键,其值即为 "Sql Server":
<appSettings>2
<add key="Database" value="Sql Server" />3
</appSettings>
当需要更改为 Access 数据访问的 DLL 时,仅需要修改这个值为 "Access" 即可实现数据库访问的切换:
<appSettings>2
<add key="Database" value="Access" />3
</appSettings>这样做的好处是灵活并且维护方便简易,可以使用.NET配置相关的类可以方便地读取到这些配置内容。
使用配置可以将一些可能会改动的项及值依赖到外部的文件,当真正遇到需要改动时,仅需要修改配置文件即可让程序随之而变,这样可以无须重新编译程序,对安插新功能的DLL尤其方便灵活。
在Web项目中,应用程序的配置项将编写在 web.config 文件的 <appSettings> 节点下;对于桌面应用程序,则在 app.config 总的 <appSettings> 下,不管是 web.config 还是 app.config,使用 System.Configuartion.ConfiguartionManguager 类都可以读取其值,有其通用性,MSDN中则推荐Web项目中使用WebConfiguartionManguager,但是开发者更希望使用具备通用性的类,这样在封装数据访问的时候无须编写兼容两者的读取配置代码,即可使已生成的DLL既可在桌面程序中使用,又可在Web程序中使用。
二、使用方法
1. 引用 System.Configuration 命名空间
默认情况下是使用不到 ConfigurationManguager 类的。需要为当前项目添加对 System.Configuration 的引用。在项目“引用”文件夹右击,选择“添加引用...”,将弹出[添加引用]对话框,在“.NET”页找到 System.Configuration 并将其添加进工程引用中。

2. 使用 ConfigurationManguager 类来访问应用程序配置
应用程序配置的信息将编写在配置文件的 <appSettings> 节点下,这样便可使用 ConfigurationManguager 类来访问这些信息。使用 ConfigurationSettings 类也是可以的,但是编译后将会得到一个警告信息说明 ConfigurationSettings 已过时,建议使用 ConfigurationManguager 类。
使用 ConfigurationManguager 类读取应用程序配置是相当简单的,只需要使用 ConfigurationManager.AppSettings[键] 即可获得指定键的值。此外,ConfigurationManager.ConnectionStrings 是用于获得配置文件中的<connectionStrings>节点的内容。
在Web项目中,可以直接在 web.config 中编辑配置文件的信息。而在桌面应用程序中,默认是看不到有配置文件的,需要手工去添加,在项目右击 -> 选择添加新项 -> 选择“应用程序配置文件”,添加后将得到一份 app.setting 文件,在这份文件内加入 <appSettings> 及 <connectionStrings> 节点即可。
三、例子
下面的例子是一个封装了数据访问操作的类,以其作为演示在项目中应该如何使用 ConfigurationManguager 类的例子。
using System;2
using System.Collections.Generic;3
using System.Text;4
using System.Data.SqlClient;5
using System.Data;6
using System.Configuration;7

8
namespace DbHelper9
{10
/// <summary>11
/// SqlHelper.cs SQL 辅助类12
/// </summary>13
public abstract class SqlHelper14
{15
private static string _connectionString = ConfigurationManager.AppSettings["SQLServerConnectionString"].Trim();16

17
/// <summary>18
/// 创建普通参数19
/// </summary>20
/// <param name="parameterName">参数名称</param>21
/// <param name="value">值</param>22
/// <returns></returns>23
public static SqlParameter GetParameter( string parameterName, object value )24
{25
return new SqlParameter(parameterName, value);26
}27

28
/// <summary>29
/// 创建返回值参数30
/// </summary>31
/// <param name="parameterName">参数名称</param>32
/// <returns>创建的参数对象</returns>33
public static SqlParameter GetReturnValueParameter( string parameterName, SqlDbType dbType )34
{35
SqlParameter p = new SqlParameter(parameterName, dbType);36
p.Direction = ParameterDirection.ReturnValue;37
return p;38
}39

40
/// <summary>41
/// 创建输出参数42
/// </summary>43
/// <param name="parameterName">参数名称</param>44
/// <param name="dbType">参数值类型</param>45
/// <returns>创建的参数对象</returns>46
public static SqlParameter GetOutputParameter( string parameterName, SqlDbType dbType )47
{48
SqlParameter p = new SqlParameter(parameterName, dbType);49
p.Direction = ParameterDirection.Output;50
return p;51
}52

53
/// <summary>54
/// 执行存储过程(无输出参数)55
/// </summary>56
/// <param name="storedProcedureName">存储过程名</param>57
/// <param name="p">参数(允许0个或者0个以上)</param>58
public static DataTable Execute( string storedProcedureName, params SqlParameter[] p )59
{60
DataTable dt = new DataTable();61

62
using ( SqlConnection conn = new SqlConnection(_connectionString) )63
{64
SqlCommand comm = conn.CreateCommand();65
comm.CommandType = CommandType.StoredProcedure;66
comm.CommandText = storedProcedureName;67

68
foreach ( SqlParameter var in p )69
{70
comm.Parameters.Add(var);71
}72

73
SqlDataAdapter da = new SqlDataAdapter(comm);74

75
try76
{77
da.Fill(dt);78
}79
catch ( Exception )80
{81
dt = null;82
}83
}84

85
return dt;86
}87

88
/// <summary>89
/// 执行存储过程(有输出参数)90
/// </summary>91
/// <param name="storedProcedureName">存储过程名</param>92
/// <param name="pc">输出的参数集</param>93
/// <param name="p">参数(允许0个或者0个以上)</param>94
public static DataTable Execute( string storedProcedureName, out SqlParameterCollection pc, params SqlParameter[] p )95
{96
DataTable dt = new DataTable();97
pc = null;98

99
using ( SqlConnection conn = new SqlConnection(_connectionString) )100
{101
SqlCommand comm = conn.CreateCommand();102
comm.CommandType = CommandType.StoredProcedure;103
comm.CommandText = storedProcedureName;104

105
foreach ( SqlParameter var in p )106
{107
comm.Parameters.Add(var);108
}109

110
SqlDataAdapter da = new SqlDataAdapter(comm);111
try112
{113
da.Fill(dt);114
pc = comm.Parameters; //获得返回值参数及输出参数115
}116
catch ( Exception )117
{118
dt = null;119
}120
}121

122
return dt;123
}124

125
/// <summary>126
/// 执行 SQL 语句127
/// </summary>128
/// <param name="sql">SQL 语句</param>129
/// <param name="p">参数集</param>130
/// <returns></returns>131
public static DataTable ExecuteSql( string sql, params SqlParameter[] p )132
{133
DataTable dt = new DataTable();134

135
using ( SqlConnection conn = new SqlConnection(_connectionString) )136
{137
SqlCommand comm = conn.CreateCommand();138
comm.CommandText = sql;139

140
foreach ( SqlParameter var in p )141
{142
comm.Parameters.Add(var);143
}144

145
SqlDataAdapter da = new SqlDataAdapter(comm);146
try147
{148
da.Fill(dt);149
}150
catch ( Exception )151
{152
dt = null;153
}154
}155

156
return dt;157
}158
}159
}160

在上面的 SqlHelper 类的第15行使用了 ConfigurationManguager 来读取 <appSettings>节点下的 "SQLServerConnectionString"
这个键的值,在使用 SqlHelper 类时,只需要到 web.config(Web项目)或者 app.config(桌面应用程序项目)中的 <appSettings> 下添加这个键,例如:
<appSettings>2
<add key="SQLServerConnectionString" value="server=(local);uid=sa;pwd=;database=master" />3
</appSettings>便能正确地使用 SqlHelper 类了。
当服务器或者数据库需要改变的时候,只需要将这个键的值改为目标的服务器或者数据库即可,而无须更改或者重新编译 SqlHelper 类。
四、小结
使用配置文件能够方便地将一些将来可能会发生改变的项依赖到外部的设置项,而不是依赖在程序中,这样可以减少反复修改或者编译源文件,仅需要修改外部这份文本类型的配置文件即可。在需要对某些功能进行“切换”的时候,尤为方便好用。



浙公网安备 33010602011771号