1. 前端aspx中的代码
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml" > 6 <head id="Head1" runat="server"> 7 <title>配置Access数据库连接</title> 8 </head> 9 <body> 10 <form id="form1" runat="server"> 11 <div> 12 </div> 13 </form> 14 </body> 15 </html>
2. 后台.cs文件中的代码
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 using System.Web.UI; 5 using System.Web.UI.WebControls; 6 using System.Configuration; 7 using System.Data.OleDb; 8 9 public partial class _Default : System.Web.UI.Page 10 { 11 protected void Page_Load(object sender, EventArgs e) 12 { 13 string con_access = ConfigurationManager.AppSettings["accessCon"].ToString();//获取配置文件中的数据库连接字符串 14 Response.Write("Aceess数据库连接字符串:" + con_access);//输出获取的数据库字符串信息 15 OleDbConnection oCon = new OleDbConnection(ConfigurationManager.AppSettings["accessCon"]); 16 try 17 { 18 oCon.Open();//打开数据库连接 19 Response.Write("<script>alert('连接成功')</script>"); 20 oCon.Close();//关闭数据库连接 21 } 22 catch (Exception ex) 23 { 24 Response.Write("<script>alert(" + ex.ToString() + ")</script>"); 25 } 26 } 27 }
3. web.config中的部分代码
1 </configSections> 2 <appSettings> 3 <add key="accessCon" value="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_access.mdb"/> 4 </appSettings> 5 <connectionStrings/>