为 ASP.NET 应用程序配置数据库访问






3.88/5 (4投票s)
演示了使用 SqlDataSource 和 GridView 的所有优势的最简单方法,并允许灵活地配置 DataSource。
引言
任何尝试过 SqlDataSource
和 GridView
ASP.NET 2.0 类的人都知道,为单个表创建数据库视图表单是多么容易。但即使是这个简单的任务,如果数据库访问设置需要在运行时由最终用户更改,也会变得更加困难。
本文展示了包含数据库访问配置窗体、将这些设置保存在 Web.config 文件中并使用它们的的简便方法。
WarningManager
我创建了一个名为 WarningManager
的简单辅助类。它使用 Label
实例来显示绿色信息消息和红色警告。
应用程序和数据库
我使用了我一个项目中的数据库(MS SQL Server 2005)。它包含一个名为 payments 的数据库和其中的 departments 表。该表包含 ID、number 和 name 列。
应用程序的目的是在 GridView
中显示表记录。主要难点在于,我想让用户能够通过应用程序中的窗体来配置数据库访问设置。
好吧,我们可以手动实现 SELECT
语句并手动填充表,但这与 SqlDataSource
的自动配置相比太麻烦了,尤其是当您需要诸如数据更新之类的附加功能时。
诀窍
诀窍如下:我们将一些设置存储在 Web.config 的 appSettings
部分。它们代表服务器地址、用户 ID 和密码,以及连接字符串格式。
同时,我们创建一个工作的“开发”连接字符串,它将在保存的配置设置被替换时被替换。
SqlDataSource
让我们开始向页面添加一个 SqlDataSource
。现在我们可以使用数据源配置向导,提供开发数据库服务器地址、用户 ID 和密码。然后我们同意将 ConnectionString 保存到 Web.config 文件中并配置 SELECT
语句。
这将生成如下代码
<asp:SqlDataSource ID="SqlDataSource1"
runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:DataConnect %>"
ProviderName="System.Data.SqlClient"
OldValuesParameterFormatString="original_{0}"
SelectCommand="SELECT [id], [number], [name]
FROM [departments] ORDER BY [id]">
提及 "<%$ ConnectionStrings:DataConnect %>"
值 - 它表示 DataSource 将 *自动* 从 Web.Config 中读取 DataConnect
ConnectionString。
我们还将一个 GridView
添加到页面,并将其 DataSourceID
属性设置为 SqlDataSource1
。
Web.config
现在我们打开 Web.config 文件,并在 appSettings
节点中添加四个参数。文件应该如下所示
<configuration>
<appSettings>
<add key="sConnectionString"
value="Data Source={0};Initial
Catalog=payments;Persist Security Info=True;
User ID={1};Password={2}" />
<add key="sServer" value="localhost" />
<add key="sUsername" value="payments_user" />
<add key="sPassword" value="pPassword" />
</appSettings>
<connectionStrings>
<add name="DataConnect" providerName="System.Data.Sql"
connectionString="Data Source=localhost;Initial
Catalog=payments;Persist Security Info=True;User
ID=payments_user;Password=pPassword" />
</connectionStrings>
<system.web>
<compilation debug="true" />
<authentication mode="Windows" />
</system.web>
</configuration>
很好。现在我们需要编辑这五个节点的***值,我们的 DataSource 将自动绑定到新服务器。
设置窗体
我们添加另一个页面来访问配置窗体,并向其中添加以下字段
<table ID="Table1" runat="server" style="width: 352px">
<tr runat="server">
<td runat="server">Server</td>
<td runat="server" style="width: 132px">
<asp:TextBox ID="ServerBox" runat="server"
Width="136px"></asp:TextBox>
</td>
</tr>
<tr runat="server">
<td runat="server">User ID</td>
<td runat="server" style="width: 132px">
<asp:TextBox ID="UserBox" runat="server"
Width="136px"></asp:TextBox>
</td>
</tr>
<tr runat="server">
<td runat="server">Password</td>
<td runat="server" style="width: 132px">
<asp:TextBox ID="PasswordBox" runat="server"
TextMode="Password" Width="136px"></asp:TextBox>
</td>
</tr>
<tr runat="server">
<td runat="server">Confirm password</td>
<td runat="server" style="width: 132px">
<asp:TextBox ID="PasswordBox1" runat="server"
TextMode="Password"
Width="136px"></asp:TextBox>
</td>
</tr>
<tr>
<td runat="server" colspan="2">
<asp:Label ID="WarningLabel" runat="server"
Font-Bold="True" ForeColor="Red"
Text="Label"></asp:Label>
</td>
</tr>
<tr runat="server">
<td runat="server" colspan="2" style="text-align: right;">
<asp:Button ID="TestButton" runat="server"
Text="Test Connection"
OnClick="TestButton_Click" CssClass="button"
Width="160px"/>
<asp:Button ID="SaveButton" runat="server" Text="Save"
OnClick="SaveButton_Click" CssClass="button"
Width="82px" />
</td>
</tr>
</table>
第一个按钮用于测试连接,第二个按钮用于保存设置。
在页面初始化时,我们使用 ConfigurationManager
类从 Web.config 文件读取值,并填充 Server 和 User 字段。
private WarningManager wm = null;
protected void Page_Init(object sender, EventArgs e)
{
wm = new WarningManager(WarningLabel);
ServerBox.Text = ConfigurationManager.AppSettings["sServer"];
UserBox.Text = ConfigurationManager.AppSettings["sUsername"];
PasswordBox.Text = "";
PasswordBox1.Text = "";
}
protected void Page_Load(object sender, EventArgs e)
{
wm.HideWarning();
}
表中的 WarningLabel
用于显示测试结果。我们使用 WarningManager
来显示这些结果。
测试连接的代码很简单:我们组合连接字符串并尝试连接到服务器
protected void TestButton_Click(object sender, EventArgs e)
{
if (PasswordBox.Text != PasswordBox1.Text)
{
wm.ShowWarning("Passwords don't match");
return;
}
wm.HideWarning();
string connectionString = String.Format(
ConfigurationManager.AppSettings["sConnectionString"],
ServerBox.Text, UserBox.Text, PasswordBox.Text);
SqlConnection conn = new SqlConnection(connectionString);
try
{
conn.Open();
if (conn.State == ConnectionState.Open)
wm.ShowInfo("Connection OK");
}
catch
{
wm.ShowWarning("Connection failed");
}
finally
{
conn.Close();
}
}
更难处理的是保存设置,因为静态 ConfigurationManager
不保存设置。因此,我们使用 System.Web.Configuration
命名空间和 WebConfigurationManager
类。保存设置的代码如下
protected void SaveButton_Click(object sender, EventArgs e)
{
if (PasswordBox.Text != PasswordBox1.Text)
{
wm.ShowWarning("Passwords don't match");
return;
}
wm.HideWarning();
Configuration config =
WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["sServer"].Value = ServerBox.Text;
config.AppSettings.Settings["sUsername"].Value = UserBox.Text;
config.AppSettings.Settings["sPassword"].Value = PasswordBox.Text;
config.ConnectionStrings.
ConnectionStrings["DataConnect"].ConnectionString =
String.Format(
ConfigurationManager.AppSettings["sConnectionString"],
ServerBox.Text, UserBox.Text, PasswordBox.Text); ;
try
{
config.Save();
}
finally { }
}
就是这样
好的,我们准备好了。我们在 Default.aspx 页面上添加另一个标签来显示当前使用的 ConnectionString,并添加两个链接以便在页面之间跳转。准备就绪。现在您可以转到设置配置页面,更改设置,测试连接(如果需要),然后保存设置。Web.config 文件将被更新,并且下次加载 Default.aspx 页面时,SqlDataSource1
将读取新的 ConnectionString 并加载数据。