使用C#来手动连接 Access 2007数据库

时间:2022-12-28 13:31:05

  首先新建一个Windows窗体,然后在窗体上拉一个Button控件和一个listbox控件,然后双击Button按钮,再在其双击事件的处理程序中写入其下代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 //引入命名空间
10 using System.Data.OleDb;
11 
12 namespace WindowsFormsApplication1
13 {
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19         }
20 
21         private void button1_Click(object sender, EventArgs e)
22         {
23             //连接数据库
24             OleDbConnection con = new OleDbConnection();
25             //在Data Source中写明 Access 2007的文件的路径
26             con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\pm\\Desktop\\1.accdb";    
29             con.Open();
30             OleDbCommand cmd = new OleDbCommand();
31             cmd.Connection = con;
32             cmd.CommandText = "select * from 1";//1是表名
33             OleDbDataReader reader = cmd.ExecuteReader();
34             while (reader.Read())
35             {
36                 listBox1.Items.Add(reader.GetValue(0));
37             }
38             reader.Close();
39             con.Close();
40         }
41     }
42 }