C# ASP.NET 数据库连接ACCESS2010

时间:2022-09-07 20:20:36

连接access2010数据库。

要添加命名空间。,这里旨在前面添加了一个gridview控件,来绑定数据,button控件没有实际的作用。,.accdb数据库放在E盘下。DataBase1数据库中有一个表userinf

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

namespace WebApplication2
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { DataBind(); }
        }
             void DataBind()
        {
            OleDbConnection conn = new 
             OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Database1.accdb");
            //这里,   @是解决转义字符串或者把后面的\全部变为\\,如
            //OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Database1.accdb");
                 conn.Open();
            OleDbCommand cd = new OleDbCommand("select * from userinf where UClass='数媒一班' ", conn);
            OleDbDataReader dr = cd.ExecuteReader();
            GridView1.DataSource = dr;//设置datagrid控件数据源
            GridView1.DataBind();//绑定到datagrid控件
            conn.Close();
        }

             protected void Button1_Click(object sender, EventArgs e)
             {

             }
        }
    }