首先,建立一个OleDbCmdTest.aspx
代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OleDbCmdTest.aspx.cs" Inherits="OleDbCmdTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>演示OleDbCommand类</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
在OleDbCmdTest.aspx.cs中写入如下代码:
protected void Page_Load(object sender, EventArgs e)
{
//连接字符串
String sqlconn = " Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\工作\\asp.net\\ASP.NET 4.0基础教程\\源代码\\chap08\\chap08\\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();
//获取数据之前,必须不断的调用Read方法,它负责前进到下一条记录.
Response.Write("<h3>使用OleDbCommand类读取数据</h3><hr>");
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>");
//关闭SqlDataReader
myReader.Close();
//关闭与数据库的连接
myConnection.Close();
}
在写入代码之前,需要引入一些包:
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
运行结果如下:
其中重点有:
1:
OleDbConnection myConnection = new OleDbConnection(sqlconn);
//打开数据库连接
myConnection.Open();
OleDbCommand myCommand = new OleDbCommand("select * from 运货商", myConnection);
OleDbDataReader myReader;
myReader = myCommand.ExecuteReader();
2:
for (int i = 0; i < myReader.FieldCount; i++)
{
Response.Write("<td>" + myReader.GetName(i) + "</td>");
}
Response.Write("</tr>");
3:
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>");