Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

aspnet6

The document provides an overview of ADO.NET, a part of the Microsoft .NET framework used for data access in applications. It covers key components such as DataSet, Data Provider, and the architecture of connected and disconnected models, along with classes like Connection, Command, DataReader, DataAdapter, and DataSet. Additionally, it explains the use of GridView and Repeater controls for displaying data in a web application.

Uploaded by

ritenpanchasara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

aspnet6

The document provides an overview of ADO.NET, a part of the Microsoft .NET framework used for data access in applications. It covers key components such as DataSet, Data Provider, and the architecture of connected and disconnected models, along with classes like Connection, Command, DataReader, DataAdapter, and DataSet. Additionally, it explains the use of GridView and Repeater controls for displaying data in a web application.

Uploaded by

ritenpanchasara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

SHREE SWAMI VIVEKANAND COLLEGE

SURENDRANAGAR
CLASS:- BCA/BSCIT SEMESTER -5
SUBJECT:- Asp.net
Prepared By:- Bhartiba parmar
Chapter-4
ADO.NET
• Contents
Introduction of ADO.NET
Component of ADO.NET
Understanding Data Provider
ADO.NET Architecture
GridView Control
Reapter Control
Introduction of ADO.NET
• Most application require some form of data access.
• ADO.NET is a part of the Microsoft .NET framework.
• The full form of ADO.net is Activex Data Object.
• ADO.NET has the ability to separate data access mechanisms,data manipulation
mechanisms and data connectivity mechanisms.
• ADO.NET is a set of classes that allow applications to read and write information
in databases.
• ADO.NET can be used by any .NET language.
• We need to add System.Data namespace for work with ADO.NET.

our program ADO.NET Database


Component of ADO.NET
• The two key components of ADO.NET are
DataSet
Data Provider
DataSet represents either an entire database or a subset of database. It
can contain tables and relationships between those tables.
Data provider is a collection of components like connection, command ,
datareader,dataadapter objects.
Understanding Data Provider
• Data provider is used to connect to the database, execute commands and
retrieve the record. It is lightweight component with better performance. It also
allows us to place the data into DataSet to use it further in our application.
• The .NET Framework provides the following data providers that we can use in our
application.
.NET Framework data provider Description
.NET Framework Data Provider for SQL Server It provides data access for Microsoft SQL Server. It requires the System.Data.SqlClient namespace.

.NET Framework Data Provider for OLE DB It is used to connect with OLE DB. It requires the System.Data.OleDb namespace.

.NET Framework Data Provider for ODBC It is used to connect to data sources by using ODBC. It requires the System.Data.Odbc namespace.

.NET Framework Data Provider for Oracle It is used for Oracle data sources. It uses the System.Data.OracleClient namespace.

.NET Framework Data Provider for SQL Server Compact It provides data access for Microsoft SQL Server Compact 4.0. It requires
4.0. the System.Data.SqlServerCe namespace.
ADO.NET Architecture
Connected Architecture
• Connected architecture simple means you are connected with the
database through out your operation.
• It is faster then disconnected architecture.
• This creates more traffic to the database end.
Client Web Command Connection
Page object object database

• Connected architecture classes:-


Connection
Command
DataReader
Disconnected Architecture
• Disconnected architecture is the new concept in ADO.net.
• The disconnected name it self is the answer.
• In disconnected architecture copy of data from database is loaded and kept into
local memory of client.connetion is last only while coping the data.
• After coping the data connection is automatically lost.

Client Web DataAdapter Connection


database
Page object object

Dataset or
datatable
object
• Disonnected architecture classes:-
DataAdapter
DataSet
DataTable
DataColumn
DataRow
Difference between Connected and disconnected architecture
Connected Disconnected
It is connection oriented. It is dis_connection oriented.
Connected methods gives faster performance Disconnected get low in speed and performance.

Datareader DataSet
Connected can hold the data of single table Disconnected can hold data of multiple tables

Connected you need to use a read only forward only In Disconnected you cannot use.
data reader
Data Reader can’t persist the data Data Set can persist the data
It is Read only, we can’t update the data. We can update the data.
Connection Class:-
• It is used to establish an open connection to the SQL Server database.
• The connection object contains all of the information required to open a
connection to the database.
• Syntax:
Sqlconnection connectionobject= New Sqlconnection(“ConnectionString”);
• Properties of Connection Object
Property Description
ConnectionString Sets or returns the details used to create a connection to a data source
ConnectionTimeout Sets or returns the number of seconds to wait for a connection to open
DefaultDatabase Sets or returns the default database name
Provider Sets or returns the provider name
State Returns a value describing if the connection is open or closed
Version Returns the ADO version number

• Methods of Connection Object


Method Description
Close Closes a connection a database connection
Open Opens a database connection
Command Class
• The Command class provides methods for storing and executing SQL statements
Command allows you to specify different types of SQL Commands like Insert,
Update, Delete, Select, etc.
• Syntax:
• SqlCommand cmd = new SqlCommand(“Command String", ConnectionObject);
• Properties of Command Object
Property Description
CommandText Contains the text of a SQL query
CommandType Specifies the type of command to be executed
Connection Specifies the connection to the database
Parameters Specifies a collection of parameters for the SQL query
• Methods of Command Object
Method Description
This method is used incase you have given Transactional Commands like INSERT, UPDATE, DELETE, etc.
ExecuteNonQuery() This method returns integer value as answer. If value is > 0, this means command executed
successfully. 0 means it did not have any effect.
This method is used if you have specified SELECT. This allows command object to connect with
ExecuteReader()
DataReader which helps you to read the data.
This method is also used when you have specified SELECT command. But it returns only one value. It
returns value of First Row’s First Column.
ExecuteScalar()
For example your command was “Select * from student”, even though entire table, it will give you
value of first student’s first column.
Example:-
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=E:\student.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True");
con.Open();
string sql = "insert into stud
values(“+Textbox1.Text+”,”’+Textbox2.Text+”’);";
SqlCommand cmd = new SqlCommand(sql, con);
int ans = cmd.ExecuteNonQuery();
if (ans > 0) NO
Response.Write("Record Inserted");
Name
else
Response.Write("Problem in Query"); Insert
con.Close();
}
DataReader Class
• DataReader is used with Command object in order to read (fetch) the data. But
remember that DataReader can be used to only read the data in sequential
manner (forward only manner). You can not go back or go on particular record
directly.
• Properties of DataReader Object
Property Description
FieldCount Contains the number of fields retrieved from the query
IsClosed Contains True if the DataReader object is closed
Item Contains A collection of values that are accessible both by field name and by ordinal number
RecordsAffected Returns the number of records affected by an executed query
HasRows Gets a value that indicates whether the DataReader contains one or more rows.

• Methods of DataReader Object


Method Description
Close() Closes the DataReader object
IsDBNull() Returns True if the field contains Null
The Read method of the DataReader object is used to obtain a row from the results of the query.
Read() Each column of the returned row may be accessed by passing the name or ordinal reference of
the column to the DataReader,
Example:-
protected void btnRead_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\student.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True");
con.Open();
string sql = "select * from stud";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Response.Write("<br/>No is " + dr["no"].ToString());
Response.Write("<br/>Name is " + dr[1].ToString());
}
}
con.Close();
}
DataAdapter Class
• This plays an important role in Disconnected Architecture. DataAdapter is a
mediator which provides (fills) data into DataSet / DataTable and again updates
the data back to database.
• The DataAdapter can perform Select, Insert, Update and Delete SQL operations in
the Data Source
• Properties of DataAdapter Object
Property Description
This property works in background which generates your Select command automatically.
SelectCommand
OleDbCommandBuilder class works behind this to generate Select command automatically.
This property also works in background which generates your Delete command. If you have deleted some
DeleteCommand rows from DataSet or DataTable, OleDbCommandBuilder automatically generates Delete Command and
stores in this.
This property also works in background which generates Insert Command. If you have insert any new row in
InsertCommand
DataSet or DataTable, OleDbCommandBuilder automatically generates Insert command and stores in this.
This property also works in background which generates Update Command. If you have done some changes
UpdateCommand in DataSet or DataTable data, OleDbCommandBuilder automatically generates Update command and stores
in this.
Methods of DataAdapter Object
Method Description
Most important method of DataAdapter. This method helps you to fill the data into DataSet or DataTable. Remember
Fill that in DataAdapter we can give only SELECT command which is filled into DataSet or DataTable.

Most important method of DataAdapter. This method is used to save the changes back from DataSet / DataTable to
actual database table.

Update Before using Update() method you need to use SqlCommandBuilder class so that it can generate related INSERT,
UPDATE, DELETE, ALTER, etc. command automatically
Example:-
protected void btnDisplay_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=E:\student.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True");
con.Open();
string sql = "select * from stud";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataTable dt=new DataTable();
da.Fill(dt);
gridDisplay.DataSource = dt;
gridDisplay.DataBind();
con.Close();
Display
}
DataSet Class
• This is used if you want to load some group of tables into local
memory. You can also use DataSet to load single table data. DataSet is
collection of tables.
Properties of DataSet Object
Property Description
DataSetName Gets or sets the name of the current DataSet.
HasErrors Gets a value indicating whether there are errors in any of the DataTable objects within this DataSet.
IsInitialized Gets a value that indicates whether the DataSet is initialized.
Tables Gets the collection of tables contained in the DataSet.

Methods of DataSet Object


Method Description
Clear() Clears all the DataTables of DataSet
ReadXml() Reads XML content and data into DataSet using specified Stream or File
Allows you to select group of data from dataset. It has different methods to select the data. This is
Select
overloaded method which allows you to filter the data in variety of ways.
WriteXml() Writes the current contents of the DataSet as XML using the specified Stream or File.
Data Table
This is used if you want to load only one table into local memory.
You can add rows to a DataTable with a DataAdapter.
Properties of DataTable Object
Property Description
Columns The Columns collection is an instance of the DataColumnCollection class, and is a container object for
zero or more DataColumn objects. The DataColumn objects define the DataTable column, including the
column name, the data type, and any primary key or incremental numbering information.
The Constraints collection is an instance of the ConstraintCollection class, and is a container for zero or
more ForeignKeyConstraint objects and/or UniqueConstraint objects. The ForeignKeyConstraint object
Constraints
defines the action to be taken on a column in a primary key/foreign key relationship when a row is
updated or deleted. The UniqueConstraint is used to force all values in a column to be unique.
DataSet Gets the DataSet to which this table belongs.
Gets a value indicating whether there are errors in any of the rows in any of the tables of the DataSet to
HasErrors
which the table belongs.
IsInitialized Gets a value that indicates whether the DataTable is initialized.
PrimaryKey Gets or sets an array of columns that function as primary keys for the data table.
The Rows collection is an instance of the DataRowCollection class, and is a container for zero or more
Rows DataRow objects. The DataRow object contains the data in the DataTable, as defined by the
DataTable.Columns collection. Each DataRow has one item per DataColumn in the Columns collection.
TableName Gets or sets the name of the DataTable.
Methods of DataTable Object
Method Description
Clear() Clears the DataTable of all data.
NewRow() Creates a new DataRow with the same schema as the table.
ReadXml() Reads XML schema and data into the DataTable using the specified Stream or File

Allows you to select group of data from table. It has different methods to select the data. This is
Select
overloaded method which allows you to filter the data in variety of ways.
WriteXml() Writes the current contents of the DataTable as XML using the specified Stream or File.
DataRow Class :
This is used incase you want to add one new row into DataSet or
DataTable. You can also use DataRow to remove rows from DataSet or
DataTable.
DataColumn Class :
This is used incase you want to modify any column or you want to add
a new column to DataSet or DataTable.
GridView Control
• The GridView is the most powerful control.
• It displayes data in tabular format.
Properties of GridView
Description
AllowPaging It is used to set pagging if table data is too long.
If you set AllowPaging to true pagesize works.It breaks the pages as per size specified in PageSize
PageSize
Property.
AllowSorting It is used to sort data in gridview.
AutoGeneratedColumns It is used to automatically generate columns which are in bounded table
AutoGenerateDeleteButton Displays delete link button with records.
AutoGenerateEditButton Displays edit link button with records.
AutoGenerateSelectButton Displays select link button with records.
Caption Sets caption for GridView.
GridLines Allows you to display gridlines withing GridView.
Methods of GridView
Method Description
DataBind Allows you to bind the data with specified data source.
DeleteRow It is used to delete specified row from gridview.
UpdateRow It is used to update specified row in gridview.
Sorts the data in GridView according to two parameter.1)SortExpression
Sort
2)SortDirection
Repeater Control.
• The Repeater control is a simple container control that binds to a list
of items.
• It walks through the bound items and produces graphical elements
according to a basic rendering algorithm and the HTML templates you
supply.
• The Repeater control supports from one through five templates.
These templates, which form a tabular structure, are described in
Table.
• Repeter Control Properties
Property Description
DataSource Specify dataset or datatable as a datasource.
HeaderTemplate Specify HeaderTemplate information.
ItemTemplate Specify ItemTemplate information.
AlternatingItemTemplate Specify AlternatingItemTemplate information.
FooterTemplate Specify FooterTemplate information.
SeperatorTemplate Specify SeperatorTemplate information.
Items Specify each item inside repeater control.
Templates Supported by the Repeater Control
Template Description
HeaderTemplate This template is used to specify headings of repeater control. This
template is rendered only once before displaying any row.

ItemTemplate Determines the output format of each row in the data source. This
template is called for each item in the list and can contain data binding
expressions.

AlternatingItemTemplate Functions similarly to ItemTemplate. If you specify this template,all


odd rows i.e. 1,3,5,etc. comes under format of <ItemTemplate> and all
even rows i.e. 2,4,6,etc. comes under format of
<AlternatingItemTemplate>.
SeparatorTemplate Determines the HTML content that goes between each row. It cannot
contain data bound information.
FooterTemplate Rendered only once when all items have been rendered. It cannot
contain data bound information.

Repeater has the following structure:


<asp:repeater runat="server" id="Repeater1">
<HeaderTemplate> ... </HeaderTemplate>
<ItemTemplate> ... </ItemTemplate>
<AlternatingItemTemplate> ... </AlternatingItemTemplate>
<SeparatorTemplate> ... </SeparatorTemplate>
<FooterTemplate> ... </FooterTemplate>
</asp:repeater>
DataBinding
There are two types of DataBinding.
1)Simple DataBinding
When you connected to any single piece of information it is known as Simple DataBinding.For Example
<asp:TextBox id=”txtName” runat=”server” Text=’<%# ddl_Names.SeletedItem.Text %>’/>
In above example we bind TextBox with DropDownList. DropDownList’s selected item will be displayed as a text
of TextBox.

2)Complex DataBinding
When you connected to any single column of a table or with entire table it’s known as complex DataBinding
Controls like DropDownList,CheckBox List,RadioButtonList are known as Complex Data Bind Controls which can
be bounded to a particular column. They can show only one column.
Controls like Data Grid , Grid View or Repeater are known as Complex Data Bind Controls which can be
bounded to entire table. They can show entire table.
Example:-
DataGrid1.DataSource=dt;
DataGrid1.DataBind();

You might also like