Skip to main content
 首页 » 编程设计

c#之使用 C# Web.config 文件连接到 Access 数据库

2024年02月01日29EasonJim

我使用的是 MS Access 2013 数据库名称是“comm”,密码是“xyz@12345”

Web.config 连接字符串:

<add name="commconn" connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:/ee/comm.accdb; Jet OLEDB:Database Password=xyz@12345;" /> 

当我运行我的网站时,它仅在我的 DropDownList 绑定(bind)数据和错误是这样的地方给出错误 “密码无效。”

我使用此代码绑定(bind)我的 DropDownList :

<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="AccessDataSource1" DataTextField="share_amt" DataValueField="ID"> 
</asp:DropDownList> 
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/comm.accdb" SelectCommand="SELECT * FROM [share_amt] ORDER BY [ID]"> 
</asp:AccessDataSource> 

我在 C# 中使用 MS Access 2013 数据库和 ASP.Net。

请您参考如下方法:

看来你的问题的症结在于:

  1. 在 Web.config 中,您创建了一个名为 commconn 的数据连接对于名为“comm.accdb”的受密码保护的 Access 数据库,但是
  2. 您已尝试使用 AccessDataSource 来填充您的 DropDownList,并且 AccessDataSource 通过 DataFile= 直接引用 Access 数据库。争论; commconn数据连接与它无关。

此外,MSDN文章

Retrieving Data Using the AccessDataSource Web Server Control

说:

Note

The AccessDataSource will not connect to an Access database that is password-protected; to retrieve data from a password-protected Access database, use the SqlDataSource control.

因此,对于 App_Data 文件夹中名为“comm.accdb”的受密码保护的 Access 数据库,您需要 <connectionStrings>在 Web.config 中这样输入:

<add name="commConnectionString"  
    connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\comm.accdb;Jet OLEDB:Database Password=xyz@12345" 
    providerName="System.Data.OleDb" /> 

在您的 .aspx 页面上连同类似的内容:

<asp:SqlDataSource  
    ID="SqlDataSource1" runat="server"  
    ConnectionString="<%$ ConnectionStrings:commConnectionString %>"  
    ProviderName="<%$ ConnectionStrings:commConnectionString.ProviderName %>"  
    SelectCommand="SELECT * FROM [share_amt] ORDER BY [ID]"> 
</asp:SqlDataSource> 
<asp:DropDownList ID="DropDownList1" runat="server"  
    DataSourceID="SqlDataSource1" DataTextField="share_amt" DataValueField="ID"> 
</asp:DropDownList>