asp.net连接access数据库实例

时间:2022-09-01 13:07:04
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center;">
<table cellpadding="1" cellspacing="1" border="1"
style="width:500px; height:214px; text-align:center; border-style:solid; border-color:Lime">
<tr>
<td align="center" style="height:100%">
<asp:GridView ID="GridView1" runat="server" Height="90%" Width="90%" Caption="Student Information">
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>


 

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)//判断是否是首次加载页面
{

//与数据库连接字符串,在本示例中数据库文件放在网站数据目录,即与web.config文件在同一目录下
//该连接字符串也可以写在web.config文件的<connectionStrings> </connectionStrings>中
string ConnStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(@"Student.mdb");
//创建OleDbConnection对象
OleDbConnection conn = new OleDbConnection(ConnStr);
conn.Open();
//创建OleDbCommand对象
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from StudentInfo";
//创建OleDbDataAdapter对象
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
//填充DataSet对象
ad.Fill(ds);
this.GridView1.DataSource = ds;
//此句必须有,否则页面上显示不出数据
this.GridView1.DataBind();
if (conn.State == ConnectionState.Open)
{//判断连接状态,若连接就关闭连接。
conn.Close();
}
}
}
}