先打开新建窗体,添加一个dataGridView控件,Access文件需保存为2000年版本左右
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace 连接Access数据库
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "*.mdb|*.mdb";
if(ofd.ShowDialog() == DialogResult.OK)
{
ofd.FileName=ofd.FileName;
}
string strPath = ofd.FileName;//获取Access数据库的所在路径
string ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strPath;//设置数据库的连接字符串
OleDbConnection oleCon=new OleDbConnection(ConStr);//实例化OleDbConnection类
OleDbDataAdapter oleDap= new OleDbDataAdapter("select*from 账目", oleCon);//SQL与数据库相连接
DataSet ds=new DataSet();//实例化
oleDap.Fill(ds);//添加SQL语句并执行
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;//显示数据
oleCon.Dispose();
}
}
}