w3pop.com :: ÍøÂçѧԺ :: ASP.NET :: ASP.NET - Database Connection Êý¾Ý¿âÁ¬½Ó
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() |
ÆÀÂÛ (0)
All