AccessDataSource Controls in asp.net2.0

Source: Internet
Author: User
Tags connect sql one table variables parent directory sql injection table name visual studio
The access|asp.net| control asp.net 2.0 contains a AccessDataSource control that extracts data from an Access database to the ASP.net 2.0 (. aspx) page. The properties owned by this control are simple. The most important attribute of AccessDataSource is the DataFile property, which points to the path of the MDB file on the hard disk. Other attributes owned by AccessDataSource also have SelectCommand, which is used to set a statement that displays the result set (tables and columns) that need to be returned. SelectCommand must be defined by using SQL syntax.

In vWD, you can add AccessDataSource controls to a page in two ways. If the MDB file is added to Database Explorer as in the previous example, you can drag and drop the column name to the page, and VWD will automatically create the AccessDataSource control and the GridView to display the data. If you do not want to use the GridView or want to customize the control, you can simply add the AccessDataSource control from the tool box and install it through the Configuration Wizard. The wizard will prompt you to browse for the data file and allow you to specify SelectCommand by selecting the column in the table in the database. If you are entering a page outside of VWD, you can enter the following code as follows:

<asp:AccessDataSource>
Id= "Mysourcname"
runat= "Server"
Datafile= "Mymdbname.mdb"
selectcommand= "Select MyField1, MyField2 from MyTable" >
</asp:AccessDataSource>
The features that need to be mentioned again are simple. All you have to offer is an ID, an MDB filename, and a SelectCommand.

This article is about the content of the data source control, but recall that the data source control does not render anything visible on the page. So in order to give you a visual way to test the data source control, the next "Try" describes the basic steps of using the GridView control (evolved from the ASP.net 1 version of the DataGrid control) to display data in a table. Note that the focus of this chapter is not on the configuration and customization of the GridView, in which case the emphasis is on the data source control. In the 5th chapter that follows, the GridView control will be studied in more detail.

Try #2--connect to MDB and display data in GridView

In this case, the Northwind on the page displays information about the products that have been sold.

(1) Launch Page Editor and browse to C:\Websites\BegAspNet2Db\ch02\.

(2) Add a page named Tio-ch02-2-displayaccessdata from the Web Form template. Click the tab below to switch to Design view.

(3) at the top of the page, enter a title, such as "Connect to an MDB data source demo," and put the same text in the title of the page. Although this step is not discussed in every exercise, we recommend that you include a title and HTML text on each page so that you do not find the page you are browsing.

<title> TIO ch02-1 Display MDB Data </title>
<body>
<body>
(4) Display the tool box (Menu:view|toolbox or type ctrl+alt+x) and expand the Data panel of the tool box.

(5) Drag a AccessDataSource control to the page.

(6) The Convenience task pane for the control should appear automatically, and if the Panel does not appear automatically, you can select a new data source and click the small arrow on the top right to open the convenience task panel. Click Configure Data Source.

(7) in the Choose a database step, click the Browse button and select C:\Websites\BegAspNet 2db\app_data\northwind.mdb, and note that the designer converts the file description to a relative reference, that is, the symbol (~ ) represents the root directory of the site.

(8) In the Configure Select Statement dialog box, select the Specify Columns option and select the Products table. Click the asterisk to select all columns. Click Next, select Query, and finish.

(9) Select the data control and display the Properties window by pressing F4. Change its ID to northwindproducts.

(10) Return to the data panel of the Toolbox, double-click on the GridView to add the control to the page and enter common Tasks Menu, and then click Choose Data Source. Select Northwindproducts and end the wizard.

(11) Select the GridView and change its ID to northwindproducts. The page should look like the following:

<%@ page language= "VB"%>
<body>
<form runat= "Server" >
<asp:accessdatasource id= "Northwindproductsaccdatasource" runat= "Server"
Selectcommand= "Select * FROM Products"
Datafile= "~/app_data/northwind.mdb" >
</asp:accessdatasource>
<asp:gridview id= "Northwindproductsgridview" runat= "Server"
Datasourceid= "Northwindproductsaccdatasource" >
</asp:gridview>
</form> </body> (12) Open the browser and view the C:\Websites\BegAspNet2Db\ch02\ch02_TIO_2_ dis-playaccessdata.aspx (see Figure 2-2).

Figure 2-2

(13) The last action is to display data from MDB query instead of a table. Close the browser and return to VWD. Ch02_tio_2_displayaccessdata-query.aspx Save the file with the new name. Select the GridView and open its common Task Menu by clicking the small arrow at the top right of the control. Click Configure Data source and next to skip the selection of the MDB file. On the interface of Configure Select statement, change the name to "Sales category" and click the asterisk to get all the fields. This query uses joins to combine four tables, limit the number of records used in one table, and obtain totals by grouping and aggregating operations on some data. Click Next, and then Test the query and finish. The data source control should look like the following:

<asp:accessdatasource id= "Northwindproductsaccdatasource" runat= "Server"
Selectcommand= "Selcet * from [Sales by Category]"
Datafile= "~/app_data/northwind.mdb" >
</asp:accessdatasource>


(14) Open the browser and view the page.

Example Description #2--connects to an MDB and displays data in GridView

You have two controls on the page. The first is AccessDataSource, which performs all the work connected to the Ado.net object, and these objects connect to the jet engine that interacts with the MDB file. The second is the GridView, which is used to get the data and convert it into the HTML format that the page can display. Note that it is important to have a meaningful name (ID) for each control. You must then determine that the data-bound control (GridView) uses its DataSourceID property to refer to the AccessDataSource's ID so that AccessDataSource can be used as its data source.

Displaying data from a query is not very difficult; in Access you can use the query name without the table name. Here are two instructions. First, if a table or query has spaces between the names, you must enclose the entire name in square brackets. Second, the techniques that require user input (for example, "Sales in a specified year" need to know which year) are not covered in this book.

After you complete the previous steps, you can see the data from the AccessDataSource control displayed on the page. The GridView is described in more detail in later chapters, but this chapter will continue to focus on data source controls.

  Select a variable in a statement

When you create a data source in vWD, the wizard will ask you to specify the columns you want to display or to create a custom SQL statement. In the previous "Try it," you simply select a few columns. You can specify more complex SQL statements in several different ways:

Use an interactive dialog box

Enter a custom SQL statement in the AccessDataSource Wizard (called by the Configure Data source shortcut task in the control)

Enter statements in the property grid

Enter statements directly in the markup of the source view

Selecting a column in the Access DataSource Wizard is a preferred technique for simple queries that return one or more columns from a separate table, because it reduces the errors caused by typography and grammar (see Figure 2-3). In this wizard, you can select the name of a table or query from the name Drop-down list. You can then select all Columns (*), or any set of columns, to choose the columns you want in the table or query. If you click the Order by button, you can sort by any column in the data source. If the first column has a constraint, the field selected in then by will be used. When you select an option from the wizard, note that the actual SQL syntax for SelectCommand also appears in a read-only text box.

Figure 2-3

Use the Where button in the wizard to create an SQL statement with parameters, which will be covered in chapter 9th. We will now skip this choice, but it is important that you use the parameters that will be discussed later in this book before you deploy. In a deployed site, avoid connecting the user's input directly to the SQL statement. Ignoring parameter problems will expose the site to the risk of SQL injection attacks. This attack technique uses false characters that are entered from the user to invalidate the original SQL statement and then replaces it with a destructive statement. You can use the parameter collection to send user input to the Ado.net parameter collection, which reduces the problem of SQL injection by leveraging the functionality of the collection.

Although the Configure Data Source Wizard has many options to help you create SQL statements quickly, there are times when you need to enter (or modify) SQL statements directly in the markup's SelectCommand. These operations are allowed by the AccessDataSource Wizard. In the Select table, query, and Column wizard pages, you can select the radio button "Specify a custom SQL statement or stored procedure." When you select this option in the wizard page, clicking the Next button will go to another page where you can enter a custom statement directly into the text area. You can also use visual Studio QueryBuilder to visually create custom statements, and the tools you use are very similar to those used by Access QueryBuilder.

If you do not want to use the wizard, you can choose to enter a custom SQL statement in the property grid of the AccessDataSource control, or you can switch to the source view and enter the statement in the SelectCommand property of the AccessDataSource control's markup.

There are a lot of books about SQL (like this book type andbeginning SQL Programming, ISBN 1-861001-80-0), this book provides a brief introduction in the Appendix. If you plan to learn SQL syntax, you can begin by learning the commands that return a portion of the record (top and distinct), the syntax for renaming one field (as), and the technique (JOIN) that returns fields from two associated tables. The following exercise explores some of the variables in the SQL statement.

Try #3--change the selection statement in AccessDataSource
  
In this exercise, you will display specific columns and specific records from the Northwind Products table. A page is also created to display the data that is obtained from the query. Please note that in this exercise, the selection rule is already in the source code. Currently, user input has not been selected as an option.

(1) Create a file named Ch02_tio_3_alternateselect-commands.aspx in C:\Websites\BegAspNet2Db\ch02\.

(2) Add a AccessDataSource control with Northwind as the ID and set the MDB to \app_data\northwind.mdb. In a series of dialog boxes, set the Select command to get all the fields ("name" =products) from the Products table. Look at the source view and note the statement you created, as follows:

SELECT * FROM Products

(3) Add the GridView, set the ID to Northwind, and set the data source to Northwind. As shown below is the entire page so far:

<%@ page language= "VB"%>


ch02 TIO 3 alternate Select conimands


ch02 TIO 3 alternate Select coinmands



Selectcommand= "SELECT * FROM Products"
Datafile= "~/app_data/northwind.mdb" >

Datasourceid= "Northwindaccdatasource" >



(4) Now open the page in the browser and note the interface shown in Figure 2-4 (no columns are displayed in the screenshot).

Figure 2-4

(5) Return to Design view and select AccessDataSource (not GridView). Open its Convenience task pane and click Configure Data Source. In the Configure Select Stat ement window, select Specify a custom SQL statement and click Next. Modify the SQL statement in the editor as follows:

SELECT * FROM [Products] WHERE (categroyid=3)

(6) Click Next and test the query. Click OK to close the dialog box. Look at the page in Source view and note the following code:

Selectcommand= "SELECT * from [Products] WHERE (CategoryID = 3)"
Datafile= "~app_data/northwind.mdb" >

(7) Try using a dialog box to create some of the following select commands, or you can enter them in the source view, or use them together.

SELECT * FROM products WHERE ProductID = 12
SELECT * from the products WHERE ProductName = ' northwoods cranberry sauce '
SELECT * from the products WHERE ProductID <11
SELECT * from the products WHERE ProductID <11 ORDER by ProductName Ascending
SELECT * from the products WHERE SupplierID = 6 OR SupplierID = 8
SELECT * FROM products WHERE SupplierID = UnitPrice > 10

Example Description #3--Change the selection statement in AccessDataSource

In the first few steps, a AccessDataSource control and a GridView are created as before. But then we started experimenting with the SELECT statement. Adding and removing columns by check boxes is most intuitive. You can also enter (or edit) the SQL statement directly in the editor window.

Added a WHERE clause to restrict the records returned from the MDB file. If the column name does not contain spaces, you can omit the square brackets. If you include a space in the column name, you must use these brackets.

   the variables in the MDB file location

The MDB file is saved in various physical locations on your hard disk: the same folder as the Web page, a subfolder under a Web page, or another folder in your machine. In the visual Web developer, these files are often browsed in the designer, and the correct path to the MDB file has been entered. However, if you intend to enter your own code, you will also need to follow the syntax described in this section.

The DataFile property of the AccessDataSource control contains a page path that can be fully qualified (for example, starting with a drive letter), or it can be specified relative to the location of the page containing the AccessDataSource. The path can also be relative to the application, that is, using the URL syntax to refer to the path. This syntax replaces the symbol (~) with the application root directory, for example: ~\app_data\produces.mdb. Using a path relative to an application makes it easier to move a page from one location to another without breaking references to the database, so it is recommended that you use a path relative to the application whenever possible.

First, let's look at the fully qualified path syntax, which contains the entire path of the MDB file, beginning with the root directory of the computer drive where the file resides:

<asp:accessdatasource ...

Datafile= "C:\WebSites\WebApplication\App_Data\MyMdb.mdb" >
Although this syntax can be used, its disadvantage is that it reduces the portability of the application. If you want to move the application to another machine, the fully qualified path to the drive or file will be different, and you will need to modify the DataFile property each time you move the page.

An improvement to a fully qualified path is the use of relative path syntax, which only needs to specify a part that is not the same as the fully qualified path of the page containing the AccessDataSource. The following is the path syntax for the database file in the same folder as the page, specified as a relative path:

<asp:accessdatasource ... datafile= "Mymdb.mdb"
Because the pages and MDB files are in one directory, the paths to these files are not different; therefore, you only need to specify their own file names. If the MDB is in the next or more level directory of the folder, the following syntax is very similar to the preceding. In such cases, you only need to specify the subfolder name and then add the slash and MDF file name:

<asp:accessdatasource ... datafile= "Mydaughterfolder/mymdb.mdb"
If the MDB file is in the parent directory of the page directory, you can also use the double-period syntax to specify the top level of the current location:

<asp:accessdatasource ... datafile= ". /mymdb.mdb ">
By using relative path syntax, you can easily move an application from one place to another without changing the path of the MDB file. Because pages and MDB files are always inseparable (if the MDB file is part of the application), the relative positions of these files are always kept consistent. But what happens when you plan to move a path within your application, such as moving a page into a subdirectory? In this case, the relative position between the page and the MDB file has changed, so the relative path syntax is not correct.

The application-relative syntax solves the problem. At this point, the path is always specified relative to the application root directory, not the page itself. The root is represented as a symbol (~):

<asp:accessdatasource ... datafile= "~app_data/mymdb.mdb>
You can now easily move the application, or move the page within the application without changing the reference to the database. Therefore, you should use the application-relative path whenever possible.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.