使用OleDBCommand相关操作类需要引入System.Data.OleDb命名空间。
通过连接一个带密码的access数据库 读取其中的数据并置入表格中显示,验证连接和命令使用正确性。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//数据库连接,记录集的获取
//注意更改路径
String sqlconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = E:/pro/web/access_test/app_data/Northwind.mdb;Jet OLEDB:Database Password=111111";
OleDbConnection myConnection = new OleDbConnection(sqlconn);
myConnection.Open();
OleDbCommand myCommand = new OleDbCommand("select * from 运货商", myConnection);
OleDbDataReader myReader;
myReader = myCommand.ExecuteReader();
//读取记录集
Response.Write("
Response.Write("
");for (int i = 0; i < myReader.FieldCount; i++)
Response.Write("
" + myReader.GetName(i) + "");Response.Write("
");while (myReader.Read())
{
Response.Write("
");for (int i = 0; i < myReader.FieldCount; i++)
Response.Write("
" + myReader[i].ToString ()+ "");Response.Write("
");}
Response.Write("
");//关闭记录集和连接
myReader.Close();
myConnection.Close();
}
}
效果图如下:
完整项目文件已上传。