使用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("<table border=1 cellspacing=0 cellpadding=2>"); Response.Write("<tr bgcolor=#DAB4B4>"); for (int i = 0; i < myReader.FieldCount; i++) Response.Write("<td>" + myReader.GetName(i) + "</td>"); Response.Write("</tr>"); while (myReader.Read()) { Response.Write("<tr>"); for (int i = 0; i < myReader.FieldCount; i++) Response.Write("<td>" + myReader[i].ToString ()+ "</td>"); Response.Write("</tr>"); } Response.Write("</table>"); //關閉記錄集和連接 myReader.Close(); myConnection.Close(); } }
效果圖如下:
完整項目文件已上傳。