Sie sind auf Seite 1von 80

Chapter 4 (Part 1)

At the end of this lesson, you will be able to:


discuss the advantages and disadvantages of using data-driven web page. differentiate namespaces and data classes used to access the data sources. create new database using SQL Server 2005 Express Edition. use SqlDataSource. retrieve and display data from database. apply parameterized query method. perform add, delete and update records on database. Use advanced data handling techniques

Web pages using databases and other sources of data to turn static web pages into dynamic datadriven web pages. Advantages: Maintenance - Using a database makes it a lot easier to maintain data and keep it up-to-date.
Reusability

- information in databases can easily be backed up and reused as required.

Data context

- database allows to define relationship and rules for the data in the database.
Quality and timeliness of content

- databases are optimized for the storage and retrieval of data. They allow you to use and update information on live Web site almost in real time.

Disadvantages: Development time - it takes a little more time to write code to access the database containing information and populate the database with the information you require.
Dependence on the database

- The whole Web site will fail if the database fail for some reason.

Database round-trip

- when a user request a dynamic page that requires data from a database, the Web server must first make request to the database for the necessary data, and then wait for it to arrive before it can assemble and send the page the user requested. This extra round-trip means a slight reduction in performance levels from the Web server
Cost

- Full enterprise-level database solution are quite expensive.

set of computer software components that can be used by programmers to access data and data services.
It is a part of the base class library that is included with the Microsoft .NET Framework.

commonly used by programmers to access and modify data stored in relational database systems, though it can also be used to access data in non-relational sources.

The .NET framework contains several namespaces with dozens of classes devoted to database access.
Microsoft has created separate namespaces that are optimized for working with different data providers (different types of databases).

The following data provider specific namespaces are included with ADO.NET: System.Data.SqlClient:
Contains classes for connecting to Microsoft SQL Server version 7.0 or higher

System.Data.OleDb: Contains classes for connecting to a data source that has an OLE DB provider (such as Ms Access).

System.Data.Odbc: Contains classes for connecting to a data source that has an ODBC driver.
System.Data.OracleClient: Contains classes for connecting to an Oracle database server. System.Data.SqlServerCe: Contains classes for connecting to SQL Server CE.

Each data source has its own set of provider objects, but they each have a common set of utility classes as follow: Connection object:
Provides a connection used to communicate with the data source.

Command object: Used to perform some action on the data source, such as reading, updating, or deleting relational data.

DataAdapter object:
A bridge used to transfer data between a data source and a DataSet object

DataReader object:
Used to efficiently process a large list of results one record at a time. It allows records to be accessed in a read-only, forwardonly mode, i.e., records have to be accessed in sequential order; they can neither be randomly accessed nor can a record which has been processed previously be accessed again.

Parameter object:
Describes a single parameter to a command.

Visual studio 2008 includes SQL Server 2005 Express Edition, a free edition of SQL Server 2005 targeted at non-professional or hobbyist developers who want a simple database solution for building applications.
Need to create a new database. Each database contains a group of one or more database tables.

Each SQL Server 2005 Express Edition database is physically implemented as a separate file.
ASP.NET provides a special directory, App_Data, where you can place these database files for use in your ASP.NET web application.

There are many data types to choose from. So, which ones are right?

Selecting the appropriate data type for your application will help your database to function more correctly. Too large of a data type : wasted space Too small of a data type: artificial ceiling incorrect type : required data type conversion incorrect type : makes reporting more difficult Example: Zip code, money

Creating New Database Table

ASP.NET gives you flexibility in how you connect to databases. A simple way is to use data source controls, which allow you to encapsulate data access in a control that you can configure with connection and query information.

You might code data access yourself if you have complex requirements that are not met by using data source controls, or if you want to create a separate component that performs data access outside of your Web pages.
This is where the Connection and Command objects come into their element.

collection of Web controls designed to provide a declarative approach to accessing and modifying data.

enable rich capabilities for retrieving and modifying data, including querying, sorting, paging, filtering, updating, deleting, and inserting.
you can work with data without having to write a lick of data access code.

six built-in datasource controls


SqlDataSource AccessDataSource ObjectDataSource XmlDataSource

SiteMapDataSource
LinqDataSource

SqlDataSource useful for accessing data from any database that resides in a relational database. The "Sql" in the control name does not refer to Microsoft SQL Server, but rather the SQL syntax for querying relational databases. SqlDataSource control can be used to access not only Microsoft SQL Server databases, but Microsoft Access databases, Oracle databases and basically any OLEDB or ODBC-compliant data store.

The System.Data.SqlClient namespace include the following classes


SqlConnection: - Represents an open database connection to a database.
SqlCommand: - to execute a SQL statement against a SQL Server database.

SqlParameter: - Pass parameter values to a SQL command - Parameters are commonly used to limit the number of row retrieved by a Select statement SqlDataReader: - To create a data reader object, which provides an efficient way to read the rows in a result set resulted by a database query SqlDataAdapter: - to provide a link between a database and dataset

In this section, you will learn to perform common database tasks using the ADO.NETs data objects: Create & open a database connection. Retrieve & display database records. Add new database records. Update existing database records. Delete database records.

You can write following code before the <system.web> tag and inside the <Configuration> tag
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFil ename=|DataDirectory|Authors.md f;Integrated Security=True;User Instance=True"/>

The connection string has three parts when connecting to a SQL Server data source: First is the data source that means the name of the SQL server. A period (full stop) means the local server <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;

Second is the name of the database file to attach:

AttachDbFilename=|DataDirectory|Autho rs.mdf; Or alternatively AttachDbFilename=C:\mydata\App_Data\Au thors.mdf ;


Last is the type of security to use

Integrated Security=True;User Instance=True/>

you can easily change the server name, database, or authentication information without editing individual Web pages.
Additionally, you can secure the connection string using encryption.

Create and Open SQL Server 2005 Express Database Connection

In this section, you need to use the Select SQL statement to query the records from the connected database.
Syntax:
Select column1, column2 From table1, table2. Where search_condition

Example:
Select au_fname, au_lname

From Authors Where au_lname = Smith


You need to use the SqlCommand class to create

the Command object that will execute the Select SQL statement and then retrieve the desired records out from the database.

Prefix: cmd >> cmdxxx.

SqlCommand CmdXXX = new SqlCommand(SQL_statement, connection_object);

where, SQL_statement : Contained SQL statement. Connection_object: name of the connection object.

You also need to use the SqlDataReader class to create the Data Reader object that will temporary store the records that retrieved by the Command object.
Prefix: dtr >> dtrXXX
SqlDataReader dtrXXX; // ExecuteReader() execute the command & return more than one value dtrXXX = command_object.ExecuteReader();

or

SqlDataReader dtrXXX = command_object.ExecuteReader();

4 steps to execute a Select statement:


1. Create & open a database connection. 2. Create a database command that represents the SQL Select statement to execute. 3. Execute the command with the ExecuteReader() method returning a DataReader. 4. Loop through the DataReader displaying the results of the query.

Retrieve & Display Database Records

Theory:
The DataReader represents a forward-only stream

of database records. The DataReader represents only a single record at a time. To fetch the next record in the stream, you must call the Read() method. To display all the records returned from a query, you must call the Read method repeatedly until you reach the end of the stream. Once you pass a records, there is no going back.

Use the DataReader property: HasRows


If (dtrAuthors.HasRows) { // display the records } else Response.Write (No records retrieved);

The HasRows property returns the value true or false. Unlike the Read() method, it does not advance the DataReader to the next row. DataReader does not have a property that returns a count of records.

When you need to retrieve only a single value?


Example: Retrieve a users password. Retrieve a single value concern aggregate

functions:
SQL Server Express supports several aggregate functions in a SQL statement, such as count(*), sum(field), avg( ), min( ), max( ).

Example
Select count(*) From Product;

Select Min(Benefits) From Employees Where Position = Manager;


Select sum (s.qty * p.unit_price) From Product p, sell s Where p.Pid = s.Pid;

If you only need to retrieve a single value from a query, then use the ExecuteScalar ( ) method that belongs to the SqlCommand.
ExecuteScalar ( ) returns the value of the first column of the first row returned by a query. # Is there any problem if you use this method in the previous example?

Retrieve a Single Database Value

When will we use it?


Example: Search products information based on product ID. Login to your e-mail.

2 methods:
a. Using string concatenation.
b. Using the Parameterized query method

a. Using String Concatenation Method


Meant part of the SQL Select statement is concatenate with value that pass from the server control.

String Concatenation

b. Using Parameterized Query Method


You represent the parameters in ADO.NET with SqlParameter. A Command (SqlCommand class) object has a parameter collection that represents all of its parameters. Create & associate:
Command_object.Parameters.AddWithValue

(@Parameter_name, input_value);

Example: CmdSelect.Parameters.AddWithValue( @firstname, Fred); We do not specify the data type of the parameter in the above statement.
If no data type has been specified, it is automatically inferred from the value assigned to the parameter. In the example above, the value Fred is a String, the data type varchar is inferred.

Using Parameterized Query

Using parameterized query makes tasks for doing query much easy and simple Your query is more readable
Preventing SQL Injection attacks

is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed.

effective measures that can be adopted to prevent SQL injection attacks:


Prevent unauthorized access to the database and

limit the permissions that are granted to the database user account that the application uses. Validate user input properly before using it, stripping off the potentially malicious characters. Always use parameterized SQL queries and stored procedures rather than building the SQL statements dynamically. (best defense against SQL injection ) Avoid displaying the actual database errors or messages to the end users.

SQL Injection

Add new records to a database table by using the SQL Insert command. Syntax:
Insert Into Tablename (field1, field2,.) Values (value1, value2,)

Example: given a table Student ( Sid, name, sex) Case: Enter new student information
Insert Into Student (Sid, name,

sex) Values (s001, superman, f )

Please learn how to insert integer value and date value

Example: Assign into string variable


String name) String name) strInsert = Insert Into Student (Sid, Values (s002, wondergal); strInsert = Insert Into Student (Sid, Values (@id, @name);

3 basic steps to execute a SQL Insert command in an ASP.Net page:


1 2 3 Create and open a database connection. Create a database command that represents the SQL Insert statement to execute. Execute the command with the ExecuteNonQuery( ) method. (since the SQL statement does not return any records, then we will use the ExecuteNonQuery( ) method, instead of using ExecuteReader( ) or ExecuteScalar( ) method.

Add New Database Records

Update existing records in a database table using the SQL Update command.
Syntax:
Update table Set column1 = value1 , column2 = value2.. Where search condition

Example:
Update Student Set sex = f Where SId = S001

3 basic steps to execute the SQL Update command:


Create and open a database connection. Create a database command that represent the SQL Update statement to execute. Execute the command with the ExecuteNonQuery ( ) method.

Unlike SQL Insert command, Update command might affect more than one record at a time.
When you execute an Update command, it changes every record that satisfies the commands Where clause. Grabbing the value returned by the ExecuteNonQuery ( ) method.

Update Existing Database Records

Delete data from a database by using the SQL delete statement. Syntax:
Delete From table Where search condition

Example:
Delete From Student Where sex = f

3 basic steps to execute a SQL Delete statement:


Create and open a database connection. Create a database command that represents the SQL Delete statement to execute. Execute the command by calling the ExecuteNonQuery ( ) method.

Until now, we only fetched one set of data from a database DataSet has the ability to hold more than one set of data. Have a Tables collection containing a Table object for each set of data. Each table in turn has a Rows collection with a Row object for each row of data. A DataSet may have several DataTables, and each DataTables may in turn consists of many rows or records.

DataSet Table Tables Table Collection

DataTable
DataRow Rows DataRow DataRow Collection

Table

The DataTable object is held in Tables collection as part of DataSet.

Each DataTable contains Rows collection.

Datasets store a copy of data from the database tables. Datasets can not directly retrieve data from Databases. DataAdapters are used to link Databases with DataSets.

DataSet Table database

DataAdapter
(Fill method)

..

Connecting Data to the DataSet with DataAdapter Objects

1. Declare an instance of the SqlDataAdapter.


2. Initialize the instance with a SQL statement

and connection instance. 3. Call Fill method of SqlDataAdapter to fill data into DataSet

Accessing data in DataSet


DataSet storing ONLY ONE record / row.

<variable> = <DataSet>.Tables[tblName].Rows[0][fieldName;

DataSet storing MORE THAN ONE record /

row.
foreach(DataRow <row> in <DataSet>.Tables[tblName].Rows) { // operation to be performed on every row }

purpose to bridge the gap between the disconnected DataTable object and the physical data source. It is capable to executing a SELECT statement on a data source and transferring the result set into a DataTable object. capable of executing the standard INSERT, UPDATE, and DELETE statements and extracting the input data from a DataTable object.

The commonly used properties offered by the SqlDataAdapter class are shown in the following table

Advanced Data Handling Using DataSet

Update, Insert, Delete using SqlDataAdapter

The following table presents a comparison of the ADO.NET DataSet and data reader classes.

Advantages and disadvantages of using datadriven web page. Namespaces and the data classes used to access data sources. Usage of SqlDataSource Retrieve and display data from database. Parameterized query method. Add, delete, update on database Advanced data handling

Das könnte Ihnen auch gefallen