📄 aspnet03-02.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><!-- saved from url=(0076)http://msconline.maconstate.edu/tutorials/aspnet20/ASPNET03/aspnet03-02.aspx --><title>ASP.NET Tutorial</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link href="aspnet03-02_data/stylesheet.css" type="text/css" rel="stylesheet">
<style>TABLE#BookGrid TD {
FONT-SIZE: 11pt; FONT-FAMILY: times new roman
}
TH {
FONT-SIZE: 11pt; FONT-FAMILY: times new roman
}
TABLE#BookGrid1 TD {
FONT-SIZE: 11pt; FONT-FAMILY: times new roman
}
TH {
FONT-SIZE: 11pt; FONT-FAMILY: times new roman
}
</style>
<meta content="MSHTML 6.00.2900.2180" name="GENERATOR"></head><body onscroll="document.all.PageScroll.value=document.body.scrollTop" onload="document.body.scrollTop=document.all.PageScroll.value">
<form id="ctl00" name="ctl00" action="aspnet03-02.aspx" method="post">
<div><input id="__VIEWSTATE" value="/wEPDwULLTExODkxMTk4MDkPZBYCAgEPZBYEAgUPPCsADQIADxYEHgtfIURhdGFCb3VuZGceC18hSXRlbUNvdW50AgVkDBQrAAQWCB4ETmFtZQUGQm9va0lEHgpJc1JlYWRPbmx5aB4EVHlwZRkrAh4JRGF0YUZpZWxkBQZCb29rSUQWCB8CBQhCb29rVHlwZR8DaB8EGSsCHwUFCEJvb2tUeXBlFggfAgUJQm9va1RpdGxlHwNoHwQZKwIfBQUJQm9va1RpdGxlFggfAgUJQm9va1ByaWNlHwNoHwQZKVtTeXN0ZW0uRGVjaW1hbCwgbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5HwUFCUJvb2tQcmljZRYCZg9kFgwCAQ9kFghmDw8WAh4EVGV4dAUFREI0NDRkZAIBDw8WAh8GBQhEYXRhYmFzZWRkAgIPDxYCHwYFFkFjY2VzcyBEYXRhYmFzZSBEZXNpZ25kZAIDDw8WAh8GBQUzNC45NWRkAgIPZBYIZg8PFgIfBgUFREIzMzNkZAIBDw8WAh8GBQhEYXRhYmFzZWRkAgIPDxYCHwYFE0RhdGFiYXNlIFByb2Nlc3NpbmdkZAIDDw8WAh8GBQYxMzYuNjVkZAIDD2QWCGYPDxYCHwYFBURCMjIyZGQCAQ8PFgIfBgUIRGF0YWJhc2VkZAICDw8WAh8GBRJEYXRhYmFzZXMgaW4gRGVwdGhkZAIDDw8WAh8GBQUyOS45NWRkAgQPZBYIZg8PFgIfBgUFREIxMTFkZAIBDw8WAh8GBQhEYXRhYmFzZWRkAgIPDxYCHwYFD09yYWNsZSBEYXRhYmFzZWRkAgMPDxYCHwYFBTY5Ljk5ZGQCBQ9kFghmDw8WAh8GBQVEQjU1NWRkAgEPDxYCHwYFCERhdGFiYXNlZGQCAg8PFgIfBgUPU1FMIFNlcnZlciAyMDA1ZGQCAw8PFgIfBgUFMjkuOTlkZAIGDw8WAh4HVmlzaWJsZWhkZAIWDzwrAA0BAA8WBB8AZx8BZmRkGAIFCUJvb2tHcmlkMQ88KwAJAQhmZAUIQm9va0dyaWQPPCsACQEIAgFkOpvlqEUJtVPFkjb92onbAsBO1zA=" name="__VIEWSTATE" type="hidden"> </div><input id="PageScroll" style="visibility: hidden; position: absolute;" name="PageScroll">
<div class="body">
<div class="divhead">Declaring Data Sources</div>
<p>Although much of the content of Web pages comes from fixed text and XHTML and
from output produced from user inputs, the majority of information comprising
modern Web sites is extracted from external data sources residing on the
server鈥攆rom databases, text files, XML files, and other such data stores. Web
page controls and scripts retrieve this external information, process it, and
display it through other server controls to create final Web page output. The
page is created dynamically, when it is requested, by embedding external
information in the output areas reserved for its display.</p>
<p>Databases are often the primary data stores for Web page information. Many of
the topics in these tutorials deal with database access and in maintaining the
currency of database information. Here, consideration is given to some basic
techniques for withdrawing that information for display on a Web page.</p>
<p>Under ASP.NET 2.0, convenient and easy-to-use methods to access database
information are introduced. These are in the form of new data source controls.
Whereas previously, database access required scripts to link to, open, extract,
and iterate records in a database, all of this processing is now encapsulated
inside single controls coded declaratively on the page.</p>
<p class="head2">The <asp:AccessDataSource> Control</p>
<p>When using a database as the source of Web page content, it is necessary to
perform a series of steps to (1) identify the server path to the database, (2)
specify the driver software to use when accessing the database, (3) open the
database for access by scripts, (4) issue an appropriate SQL statement to
retrieve fields of data from specified tables in the database, (5) iterate the
returned set of records to display them on the page, and (6) close the database
connection when done. Previous to ASP.NET 2.0, these steps required a script to
explicitly perform these actions to retrieve information for page display. Now,
most of these steps are encapsulated in and can be performed automatically
through special data source controls.</p>
<p>Figure 3-9 gives the general format for using the <span class="code"><<b>asp:AccessDataSource</b>></span> control to link to and
return a set of records from a Microsoft Access database. This control is one of
several available to work with different database products. The present format
shows control properties needed to extract database information for page
display. Later formats are introduced for performing database maintenance
activities.</p>
<table class="format" cellpadding="10">
<tbody>
<tr>
<td class="code"><pre><b><asp:AccessDataSource</b> <b>id=</b>"<i>id</i>" <b>Runat</b>="Server"
<b>DataFile=</b>"<i>path</i>"
<b>SelectCommand=</b>"<i>SQL SELECT statement</i>|<i>query name</i>"
<b>SelectCommandType=</b>"Text|StoredProcedure"
<b>DataSourceMode</b>="DataSet|DataReader"
<b>/></b>
</pre></td></tr></tbody></table>
<div class="figure"><b>Figure 3-9. </b>General format for <span class="code"><asp:AccessDataSource></span> control.</div>
<p>An <span class="code"><b>id</b></span> property must be assigned to the control
in order to identify the returned recordset to other ASP.NET controls which
display the returned records.</p>
<p>The <span class="code"><b>DataFile</b></span> property gives the directory path
to the database. This can be the physical server path beginning with the drive
letter, it can be a virtual path relative to the Web page containing the
control, or it can be a path relative to the root Web directory.</p>
<p>For the example <span class="code">BooksDB.mdb</span> database used in these
tutorials, its physical path is given by the following <span class="code">DataFile</span> property.</p><pre class="divcode">DataFile="c:\eCommerce\Databases\BooksDB.mdb"
</pre>
<div class="listing"><b>Listing 3-5. </b>Physical path specification for example
<span class="code">BooksDB.mdb</span> database.</div>
<p>Alternately, the database can be accessed through a path relative to the Web
page containing the control.</p><pre class="divcode">DataFile="../Databases/BooksDB.mdb"
</pre>
<div class="listing"><b>Listing 3-6. </b>Relative path specification for example
<span class="code">BooksDB.mdb</span> database.</div>
<p>A third alternative is to specify a path relative to the root directory (the
virtual Web directory) under which the page and database are stored. Thus, in
the path</p><pre class="divcode">DataFile="~/Databases/BooksDB.mdb"
</pre>
<div class="listing"><b>Listing 3-7. </b>Path specification for example <span class="code">BooksDB.mdb</span> database relative to root Web directory.</div>
<p>the character pair <span class="code">"~/"</span> points to the root directory
of the application (<span class="code">c:/eCommerce</span> in this example)
followed by the subdirectory path to the database. As a general rule, relative
path syntax is preferred since it is less likely to need changing when moving
applications to different servers or different directory structures.</p>
<p>The <span class="code"><b>SelectCommand</b></span> property provides two
different means to retrieve information from a database. It can supply an SQL
<span class="code">SELECT</span> statement to identify the fields to retrieve from
specified tables in the database. Any valid <span class="code">SELECT</span>
statement can be issued, either for a single table or for joined tables. The
property value also can be the name of a <b>stored procedure</b>, in the case of
an Access database, the name of a <b>Query</b>. When using a stored procedure,
the <span class="code"><b>SelectCommandType</b>="StoredProcedure"</span> property
must be coded; it is not required for its default setting <span class="code">SelectCommandType="Text"</span> for an SQL statement.</p>
<p>There are two <span class="code"><b>DataSourceMode</b></span> settings that can
be made. The default <span class="code">DataSet</span> mode stores the extracted
recordset <i>in server memory</i> where it is available for further processing
beyond its initial assignment to an information display control. This setting is
necessary, for instance, when the display control provides sorting and paging
options to rearranged and redisplayed a retrieved recordset. The <span class="code">DataReader</span> mode is used when only a single access to the
database is needed. This mode is a read-once, forward-only access method to
retrieve a recordset for one-time-only display. It is more efficient than the
<span class="code">DataSet</span> method to retrieve a single set of records. The
<span class="code">DataSourceMode</span> is optional; using the default <span class="code">DataSet</span> mode is adequate for most retrieval situations unless
server efficiencies associated with large databases come into play.</p>
<p>Assume, for instance, that a selected set of fields is to be extracted from
the <span class="code">Books</span> table of the example <span class="code">BooksDB.mdb</span> database. An appropriately coded <span class="code"><asp:AccessDataSource></span> control is shown below.</p><pre class="divcode"><asp:AccessDataSource id="BookSource" Runat="Server"
DataFile="~/Databases/BooksDB.mdb"
SelectCommand="SELECT BookID, BookType, BookTitle, BookPrice FROM Books
WHERE BookType = 'Database'
ORDER BY BookTitle"/>
</pre>
<div class="listing"><b>Listing 3-8. </b>Coding an AccessDataSource control.</div>
<p>An <span class="code">id</span> is assigned so that a display control can point
to this data source as the source for its information to display.</p>
<p>The <span class="code">DataFile</span> property gives the path to the database,
in this case expressed relative to the root directory of the Web application.
Alternate path specifications give the relative path from the page to the
database, <span class="code">"../Databases/BooksDB.mdb"</span>, or the full
physical path to the database, <span class="code">"c:\eCommerce\Databases\BooksDB.mdb"</span>.</p>
<p>The <span class="code">SelectCommand</span> property gives the SQL <span class="code">SELECT </span>statement needed to retrieve four data fields from
records in the <span class="code">Books</span> table. Only those records with a
<span class="code">BookType</span> field value of <span class="code">'Database'</span> are selected, and all records are returned in
sorted order by the <span class="code">BookTitle</span> field. When the Web page
is opened, this data source control immediately connects to the database and
retrieves the recordset, making it available for display on the page.</p>
<p class="head2">The <asp:SqlDataSource> Control</p>
<p>The AccessDataSource is a special case of the general <span class="code"><b><asp:SqlDataSource</b>></span> control used to access a
variety of database products. An SqlDataSource requires <span class="code"><b>ProviderName</b></span> and <span class="code"><b>ConnectionString</b></span> properties to make a connection to a
database.</p>
<table class="format" cellpadding="10">
<tbody>
<tr>
<td class="code"><pre><b><asp:SqlDataSource</b> <b>id=</b>"<i>id</i>" <b>Runat="Server"</b>
<b>ProviderName=</b>"<i>provider name</i>"
<b>ConnectionString</b>="<b>Provider=</b><i>provider</i>;
<b>Data Source=</b><i>path</i>"
<b>SelectCommand=</b>"<i>SQL SELECT statement</i>|<i>query name</i>"
<b>SelectCommandType=</b>"Text|StoredProcedure"
<b>/></b>
</pre></td></tr></tbody></table>
<div class="figure"><b>Figure 3-10. </b>General format for <span class="code"><asp:SqlDataSource></span> control.</div>
<p>The <span class="code">ProviderName</span> is <span class="code">"System.Data.OleDb"</span> when connecting to an Access database. The
<span class="code">ConnectionString</span> includes <span class="code"><b>Provider</b></span> and <span class="code"><b>Data Source</b></span>
parameters separated by a semicolon. For an Access database, the <span class="code">Provider</span> is <span class="code">"Microsoft.Jet.OLEDB.4.0"</span>
and the <span class="code">Data Source</span> gives the <i>physical</i> path to
the database. The following SqlDataSource retrieves the same recordset as the
previous AccessDataSource.</p><pre class="divcode"><asp:SqlDataSource id="BookSource" Runat="Server"
ProviderName="System.Data.OleDb"
ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:\eCommerce\Databases\BooksDB.mdb"
SelectCommand="SELECT BookID, BookType, BookTitle, BookPrice FROM Books
WHERE BookType = 'Database'
ORDER BY BookTitle"/>
</pre>
<div class="listing"><b>Listing 3-9.</b> Coding an SqlDataSource.</div>
<p class="head2">Using Connection Strings</p>
<p>For both the AccessDataSource and SqlDataSource controls, the coded path to a
database gives its current location, through either its relative path or
physical path. Further, across the multiple pages of a Web site, this path is
coded for every data source control appearing on all pages. This presents no
particular problem unless, that is, the location of the database, or perhaps its
name, is changed. Then it is necessary to track down and change these path
references everywhere they occur, a possibly daunting task leading to oversights
and errors.</p>
<p class="head3">Creating a Database Connection String</p>
<p>Under ASP.NET, it is possible to code the path to a database one time only;
then, if its path or name changes, a coding change can be made to this single
occurence for automatic propogation across all path references on all pages.
This single occurence of a path specification appears in the <span class="code">web.config</span> file, used previously to set up debugging
preferences. In this case, a special <span class="code"><b><connectionStrings></b></span> section is added to the file
where database connection information is coded.</p>
<p>The following rewrite of the previous <span class="code">web.config</span> file
has entries that can be used for both the <span class="code">DataFile</span>
attribute of an AccessDataSource and the <span class="code">ConnectionString</span> attribute of an SqlDataSource, both of which
include the path to the example <span class="code">BooksDB.mdb</span>
database.</p><pre class="divcode"><!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
<b>
<connectionStrings>
<add
name="AccessBooksConnection"
connectionString="c:\eCommerce\Databases\BooksDB.mdb"
/>
<add
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -