当前位置: 首页 > 网络学院 > 服务端脚本教程 > ASP.NET > ASP.NET - Database Connection 数据库连接
ADO.NET is also a part of the .NET Framework. ADO.NET is used to handle data access. With ADO.NET you can work with databases.
ADO.NET 也是.NET Framework 的一部分。ADO.NET 可用来处理数据访问。使用ADO.NET你可以操作数据库。
Database connection - Bind to a Repeater control
Database connection - Bind to a DataList control
We are going to use the Northwind database in our examples.
接下来我们将要在举例中使用Northwind 数据库
First, import the "System.Data.OleDb" namespace. We need this namespace to work with Microsoft Access and other OLE DB database providers. We will create the connection to the database in the Page_Load subroutine. We create a dbconn variable as a new OleDbConnection class with a connection string which identifies the OLE DB provider and the location of the database. Then we open the database connection:
首先,导入 "System.Data.OleDb" 命名空间,我们需要这个命名空间跟 Microsoft Access 以及其他的OLE DB 数据库提供商一起运作。我们将在Page_Load 子程序中建立到数据库的连接。我们建立的变量 dbconn 来作为一条新的 OleDbConnection 类,这需要通过一串能够让OLE DB提供商识别的饿字符串并且有于之对应的本地数据库。然后我们就打开了数据库连接:
<%@ Import Namespace="System.Data.OleDb" %> <script runat="server"> |
Note: The connection string must be a continuous string without a line break!
注意:连接字符串必须是连续的,中间不能换行!
To specify the records to retrieve from the database, we will create a dbcomm variable as a new OleDbCommand class. The OleDbCommand class is for issuing SQL queries against database tables:
要从数据库取回指定的记录,我们将要建立一个变量 dbcomm 来作为OleDbCommand 类。OleDbCommand是可针对数据表来发送SQL查询的类:
<%@ Import Namespace="System.Data.OleDb" %> <script runat="server"> |
The OleDbDataReader class is used to read a stream of records from a data source. A DataReader is created by calling the ExecuteReader method of the OleDbCommand object:
OleDbDataReader 类可用来读取来自数据源的记录流。通过调用OleDbCommand 对象中的 ExecuteReader方法就可以建立一个数据读取器:
<%@ Import Namespace="System.Data.OleDb" %> <script runat="server"> |
Then we bind the DataReader to a Repeater control:
我们将数据读取器绑定到转发器控件上:
<%@ Import Namespace="System.Data.OleDb" %> <script runat="server"> <html> <form runat="server"> <HeaderTemplate> <ItemTemplate> <FooterTemplate> </asp:Repeater> </body> |
Always close both the DataReader and database connection after access to the database is no longer required:
在不需要数据库访问的时候把数据读取器以及数据库连接都关闭掉:
dbread.Close() |