0% found this document useful (0 votes)
81 views48 pages

C Session 11

This document discusses database management in ASP.NET using ADO.NET. It begins by explaining why databases are required and provides an overview of SQL Server 2000. It then describes the master, tempdb, model, and msdb databases in SQL Server 2000. It defines tables and databases and explains how to create them. The document also covers data types, constraints, DDL, DML, SQL, and the SELECT statement. It discusses literals, querying databases, operators, and search conditions. Finally, it provides an overview of the INSERT, UPDATE, DELETE, T-SQL, ADO.NET, data providers, and opening a connection in ASP.NET using ADO.NET and SQL Server.

Uploaded by

eshamu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views48 pages

C Session 11

This document discusses database management in ASP.NET using ADO.NET. It begins by explaining why databases are required and provides an overview of SQL Server 2000. It then describes the master, tempdb, model, and msdb databases in SQL Server 2000. It defines tables and databases and explains how to create them. The document also covers data types, constraints, DDL, DML, SQL, and the SELECT statement. It discusses literals, querying databases, operators, and search conditions. Finally, it provides an overview of the INSERT, UPDATE, DELETE, T-SQL, ADO.NET, data providers, and opening a connection in ASP.NET using ADO.NET and SQL Server.

Uploaded by

eshamu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Database Management in ASP.NET Using ADO.

NET

Why Database Required

Database Management System

SQL Server 2000


It is a Relational Database Management System. Where we use to create our database to hold our data transactions. When we install it we have four default database with to manage our database creation and maintenance. 1. Master The master database records all of the system level information for a SQL Server system. It records all login accounts and all system configuration settings. 2. TempDb It holds all temporary tables and temporary stored procedures. It also fills any other temporary storage needs such as work tables generated by SQL Server.

3. Model The model database is used as the template for all databases created on a system. When a CREATE DATABASE statement is issued, the first part of the database is created by copying in the contents of the model database, then the remainder of the new database is filled with empty pages. 4. MSDB The msdb database is used by SQL Server Agent for scheduling alerts and jobs, and recording operators.

Database
It is a collection of table, used to organized the data in tables format. In SQL Server 2000 we have two associated files for each database i.e. .mdf (Main Data File) and .ldf (Log Data File) Syntax
Create database <database-name>

For HCL CDC, By: Rajinder Kr. Chitoria

Database
It is a collection of table, used to organized the data in tables format. In SQL Server 2000 we have two associated files for each database i.e. .mdf (Main Data File) and .ldf (Log Data File) Syntax
Create database <database-name>

Table
Table is a collection of rows. Before making a table we require three thing 1. Table Name 2. Column Name with restriction if any 3. Column Data Type Data Type

varchar decimal nchar smalldatetime

text Float Ntext smallint

bit image nvarchar smallmoney

Char Int Numeric sql_variant

datetime Money Real sysname

Create Table
Syntax
Create Table <table_name> ( <column_name> <datatype>, <column_name> <datatype>, <column_name> <datatype> )

Constraints
Constraints ensures the consistency and correctness of data stored in a database. It is broadly classified into the following four categories:
1. Entity Constraints
Ensures that each row can be uniquely identified by an attribute called the primary key 2.

Domain Constraints
Ensures that only a valid range of values is allowed to be stored in a column

3.

Referential Constraints
Ensures that the values of the foreign key match with the value of the corresponding primary key

Data Definition Language (or DDL)

DDL statements, as the name suggests, allow you to define the database structure. Most DDL statements begin with CREATE, ALTER, or DROP. The two DDL statements we are going to cover today are CREATE DATABASE (used for creating new databases) and ALTER DATABASE (used for altering existing databases).

Data Manipulation Language (or DML)

DML statements, on the other hand, are used for manipulating the data inside database objects. For example, the SELECT statement allows you to query the data inside a database, the INSERT statement allows for the addition of new data, the UPDATE statement updates selected data, and the DELETE statement allows you to remove data

SQL
Structured Query Language, also known as SQL, is a query and programming language. It can be used for accessing, updating, deleting, and adding data in a database. SQL can also be used for managing the RDBMS (Relational Database Management System) itself. Different databases may use versions of SQL that very slightly, but most comply with the standard ANSI SQL-92 implementation of SQL, commonly call ANSI SQL. You can group SQL statements into two main categories: 1. Data Definition Language (or DDL) 2. Data Manipulation Language (or DML).

SELECT Statement
The SELECT Statement
Enables you to access and retrieve data from a database Syntax:
SELECT [ALL | DISTINCT] select_column_list [INTO [new_table_name]] [FROM {table_name | view_name} [(optimizer_hints)][[, {table_name2 | view_name2}[(optimizer_hints)] [WHERE clause] [GROUP BY clause][HAVING clause] [ORDER BY clause][COMPUTE clause]

Using Literals
The result set of a data query statement can be made more readable by including a string called a literal in the SELECT list Literals are enclosed in single quotes and get printed exactly as they are written in the SELECT list

Syntax

Method 1:
SELECT column_heading=column_name[,column name] FROM table_name

Method 2:
SELECT column_name column_heading [,column_name] FROM table_name

Querying Database
The SELECTWHERE Statement
Retrieves and displays data with a specific condition Syntax

SELECT column_list FROM table_name WHERE search_condition

Arithmetic Operators
SQL Server supports operators that perform arithmetic operations such as addition, subtraction, division, and multiplication on numeric columns The arithmetic operators supported by SQL Server are:
+ (for Addition) - (for Subtraction) / (for Division) * (for Multiplication) % (for Modulo)

Arithmetic Operators cont..


Some rules regarding the use of arithmetic operators are:
Arithmetic operations can be performed on numeric columns or numeric constants The Modulo (%) operator cannot be used with columns of money, smallmoney, float, or real datatypes

Search Based on Condition


SQL Server provides a few methods for searching rows in a table. These methods can be broadly categorized as follows:
Logical operators (AND, OR , NOT) Comparison operators (>,<,=) Range operators ( BETWEEN AND) List operators (IN)

Logical Operator
Multiple search conditions can be combined by using the following logical operators:
ORreturns the result when any of the specified search conditions is true ANDreturns the result when all the specified search conditions are true NOT neutralizes the expression that follows it

When more than one logical operator is combined in the WHERE clause, the order of precedence is NOT, AND, and OR Parentheses can be used to change the logical order of precedence

Comparison Operators
Comparison operators allow row retrieval from a table based on the condition specified in the WHERE clause Syntax

SELECT column_list FROM table_name WHERE expression1 comparison_operator expression2

Range Operators
The range operator is used to retrieve data that can be extracted in ranges. The range operators are:

BETWEEN NOT BETWEEN


Syntax

SELECT column_list FROM table_name WHERE expression1 range_operator expression2 AND expression3

List Operators

The IN operator allows the selection of values that match any one of the values in a list The NOT IN operator restricts the selection of values that match any one of the values in a list Syntax

SELECT column_list FROM table_name


WHERE expression list_operator (value_list)

Insert Statement

After the table structure has been created, data can be inserted into the table. You can insert data into the table by using the INSERT command Syntax

INSERT [INTO] table_name [column_list] VALUES (values_list)

Update Statement
The UPDATE Statement is used to modify data in a database
Syntax UPDATE table_name SET column_name = value[,column_name = value] [FROM table_name] [WHERE condition]

Delete Statement
The DELETE Statement is used to delete a row from a table
Syntax

DELETE [FROM] table_name [ FROM table(s)] [WHERE condition]

T-SQL
T-SQL is SQL Servers enhanced version of the standard SQL programming language. T-SQL in SQL Server 2000 allows for such things as stored procedures, IF and WHILE statements, and additional functions/data types (we will cover data types when we start creating tables) that are not available in standard SQL

ADO.NET

ADO.NET is a data-access technology that enables applications to connect to data stores and manipulate data contained in them in various ways Designed for highly efficient data access Support for XML and disconnected record sets

.NET Data Provider Model

Steps of data connection and data manipulations


3 steps should be done to retrieve some data from DB 1. A connection object created to represent a physical connection to some data store (an SQL Server or an XML file). 2. A command object created to represent a directive to retrieve from (select) or manipulate (insert, update, delete) the data store. 3. A dataset object created to represent the actual data. Note that DataSets are always disconnected from their source connection and data model and can be modified independently.

DB
Connection Command DataSet

Data Providers
In ADO.NET different namespaces and classes are created to work with different data providers:
System.Data.SqlClient Microsoft SQL Server 7.0 or higher System.Data.OleDb OLE DB provider, such as Microsoft Access System.Data.OracleClient Oracle Database server.

In our course you will work with SQL Server using System.Data.SqlClient namespace.

System.Data.SqlClient
System.Data.SqlClient namespace includes 3 classes to perform data connection and data manipulation:
SqlConnection SqlCommand SqlDataReader
Database

SqlConnection

SqlCommand
SqlDataReader

Opening a connection
To work with SQL Server the following directive should be added to ASP.Net pages:
<%@ Import Namespace="System.Data.SqlClient" %>

The first step is to open a database connection. SqlConnection class is used to establish a connection to SQL Server database.
SqlConnection con; con=new SqlConnection("server=localhost;uid=sa;database=asp" ); con.open();

SqlConnection
An SqlConnection class instance should be created (con=new SqlConnection()). It is initialized by passing a connection string to the constructor of SqlConnection class. The connection string should provide all necessary location and authentication information to connect to SQL server. server=localhost;uid=sa;pwd=secret;database=asp
where server=localhost (specifies a ServerName), uid=sa (specifies a user sa=server admin), pwd (specifies a password if required),Database=asp specifies the Database Name

Finally the connection is opened by calling an open() method - con.open().

SqlCommand
An SqlCommand class represents an SQL statement (query) or a stored procedure.
SqlCommand myCommand = new SqlCommand("select * from Table", con); where a constructor specifies statement/query to perform and using which database connection.

Later this object uses an ExecuteReader() method to retrieve the result of the query. The result may return non values (ExecuteNonQuery - update) or to return a single value (ExecuteScalar - count) or to return a DataReader(ExecuteReader). If a record set is returned then it is stored in SqlDataReader object.

Partial Example
SqlConnection myConnection = new SqlConnection("server=localhost;uid=sa;database=asp"); SqlCommand myCommand = new SqlCommand( "UPDATE Table SET phone='(800) 555-5555' WHERE au_id = '123-45-6789'", myConnection); myCommand.Connection.Open(); myCommand.ExecuteNonQuery(); myCommand.Connection.Close();

SqlDataReader
SqlDataReader class represents a stream of database records returned from a SQL statement (query) or a stored procedure.
SqlDataReader dr = myCommand.ExecuteReader();

It is a forward-only, read-only access to a set of rows returned from a SQL server database. Later some control should update its DataSource property to this DataReader:
MyDataGrid.DataSource = dr; MyDataGrid.DataBind();

Final step
The final step do not forget
to close the DataReader: dr.Close(); to close the Connection: con.Close();

Example
<%@ Page Language="C#"%> <%@ Import Namespace="System.Data.SqlClient" %> <script runat=server> void Page_Load(Object sender , EventArgs e) { SqlConnection con = new sqlConnection("Server=localhost;uid=sa;database=pubs"); con.Open(); SqlCommand cmd = new SqlCommand( "Select au_name From Authors", con ); SqlDataReader dtrAuthors = cmd.ExecuteReader(); while ( dtrAuthors.Read()) { Response.Write( "<li>" ); Response.Write( dtrAuthors[ "au_name" ] ); } dtrAuthors.Close(); Read method returns true if con.Close(); there is a next record to read }</script>

Gets a value for the field called au_name

SqlDataAdapter

Between the Data Source and the DataSet Encapsulates Command Objects Fills the DataSet Updates Data Source From DataSet DataSet DataAdapter SQL

SqlDataAdapter Properties
SelectCommand Connection

CommandType
CommandText Parameters UpdateCommand InsertCommand

DeleteCommand
TableMappings

DataSet Architecture
Dataset DataTableCollection DataTable DataRowCollection DataColumnCollection ConstraintCollection

DataRelationsCollection

DataSet Architecture
Dataset
DataColumn

DataTable

DataRow

DataColumn

DataTable

DataRow

Strongly Typed DataSets

Formal .xsd declaration Classes can be generated from .xsd Allows for easy navigation of DataSet, especially with the aid of Intellisense

DataRelations in DataSets

Relations Collection
Methods Generated Cascading Updates, Deletes Binding Child Rows Visually

45

Data Source Control

Retrieving Data

Data Binding

You might also like