using System.Data.OleDb;
using System.Data.SqlClient;
string strFilePath = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" + Application.StartupPath + "\\111.accdb";
string sql = "select * from 111";
//声明一个数据连接
System.Data.OleDb.OleDbConnection con = new OleDbConnection(strFilePath);
System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
DataTable dt = new DataTable();
try
{
da.Fill(dt);
if (dt.Rows.Count >= 1)
{
dataGridView1.DataSource = dt;
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
con.Close();
con.Dispose();
da.Dispose();
}
简单说明:
1 建立连接,因为是access数据库,所以建立的是OleDbConnection
2 建立适配器OleDbDataAdapter da,目的是将数据库里的表fill到dt中,那为什么不让da直接有dt的功能?这就不用fill了!!
3 dt,说白了就是一张表,当然有dt.Rows.Count行数啊
4 dataGridView的成员DataSource就是一个DataTable,指明一下就ok了
5 记得关闭连接Close、Dispose和关闭适配器da.Dispose();
简单总结:
涉及到的类:
1 Application,它的StartupPath即debug文件
2 OleDbConnection
3 OleDbDataAdapter:肯定会需要的con和sql语句参数都用到了。2、3是不是可以连在一起?每次数据库操作都可以用这两个一起来,或这只是一种方式?
4 DataTable,表格了,它的行数.Rows.Count
5 DataGridView,这里只做显示用,应该还能在其上进行操作
6 Exception,常用的方法是:ex.ToString());