UNIT4 Database Programming With ADO
UNIT4 Database Programming With ADO
Introduction of ADO.NET
ADO is a rich set classes, interface, structures, and enumerated types that manage
data access from different types of data stores.
There are 4 Core Components of .Net Data Providers that is used to connect, access and
retrieve data from the database.
1. Connection – This component is used for connecting to the database. The base class
is DbConnection.
2. Command – This component executes SQL query against the data source. The base
class is DbCommand.
3. DataReader – It reads data from data source. It accesses data read-only and forward-
only. The base class is DbDataReader.
4. DataAdapter – It invokes dataset and resolves updates with the data source. The
base class is DbDataAdapter.
Disconnected Architecture
Connected Disconnected
It is connection oriented. It is dis_connection oriented.
Datareader DataSet
Connected methods gives faster Disconnected get low in speed and
performance performance.
connected can hold the data of single table disconnected can hold multiple tables of
data
connected you need to use a read only disconnected you cannot
forward only 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 data
Connection Object
Connection Object is used for connecting your application to data source or database. It
carries required authentic information like username and password in the connection
string and opens a connection. You need to different type of connection object for
different type of data providers. For example:
Connection String
Connection String combines all the required authentic information that is used for
connecting to a Data Source, like Server Name, Database Name, User Name, Password
etc. It is just a single line string that is used by connection object to connect to the
database.
Example:
DataReaders
The DataReader object in C# ADO.NET allows you to retrieve data from database in read-only
and forward-only mode. It means you can only read and display data but can’t update or delete
data. If you want to make modification in retrieved data you need to use DataAdapter instead of
DataReader.
Properties
PROPERTY DESCRIPTION
Methods
METHOD DESCRIPTION
Close Closes a DataRaeder object.
Read Reads next record in the data reader.
NextResult Advances the data reader to the next result during batch transactions.
Getxxx There are dozens of Getxxx methods. These methods read a specific data type value
from a column. For example. GetChar will return a column value as a character and
GetString as a string.
DataAdapters
DataAdapters are used for controlling Datasets and it provides communication between DataSets
and DataSource. DataAdapters make a connection with Data Source and then Fill Data to
DataSets. It also Updates Data Source with DataSets.
Properties:
Properties Description
DeleteCommand It is used for Deleting Records from DataSource
InsertCommand It is used for adding New Record to a DataSource
SelectCommand It is used for Selecting Records from a DataSource
UpdateCommand It is used for Updating Records in a DataSource.
TableMapping It is used for mapping actual database tables and datasets.
Methods:
Method Description
Fill This method Fills Records from DataAdapters to DataSets.
Update This method update DataSource with DataSets.
DataSet
Command
it returns first column of the first row in the result set return by the query.
It’s used Select Query with Aggregate Function(sum,count).
Dataset
It persists data in memory which is separately from the database.
By nature it is disconnected.
You can perform all DML statement.
You can load data in dataset from any data source like SQL Server, Oracle etc.
You can create table inside the Dataset even you can define the keys and create
relationship between them.
It belongs to “System.Data” namespace.
Using system.Data;
DataSet objDS = new DataSet();
Data Relation
DataTable
Every DataTable is again a collection of Rows and Columns where each row is
represented as a DataRow class and identified by its index position.
DataColumns
It is a collection Columns.
Syntax:
<datatable>.Columns[Index] OR columns[Name]
For example:
Ds.Tables[0].Columns[0] Or: Ds.Tables[0].Columns[“ENO”]
Ds.tables[0].rows[0]
DataColumn
The DataColumn is the fundamental building block for creating the schema of a DataTable.
Each DataColumn has a DataType property that determines the kind of data the column
holds.
You can simple – bind a control to column within a data table.
For example, you can restrict the data type to integers, or strings, or decimals. Because data
that is contained by the DataTable is typically merged back into its original data source, you
must match the data types to those in the data source.
This class provides the following Properties.
Property Description
AllowDBNull Gets or sets a value that indicates whether null values are
allowed in this column for rows that belong to the table.
AutoIncrement Gets or sets a value that indicates whether the column
automatically increments the value of the column for new
rows added to the table.
ColumnName Gets or sets the name of the column in
the DataColumnCollection.
DataType Gets or sets the type of data stored in the column.
ReadOnly Gets or sets a value that indicates whether the column
allows for changes as soon as a row has been added to
the table.
Unique Gets or sets a value that indicates whether the values in
each row of the column must be unique.
DataRelation
A DataRelation is used to relate two DataTable objects to each other
through DataColumn objects. For example, in a Customer/Orders relationship, the
Customers table is the parent and the Orders table is the child of the relationship. This is
similar to a primary key/foreign key relationship.
Relationships are created between matching columns in the parent and child tables. That is,
the DataType value for both columns must be identical.
This class provides the following Properties.
Property Description
ChildColumns Gets the child DataColumn objects of this relation.
ChildKeyConstraint Gets the ForeignKeyConstraint for the relation.
ChildTable Gets the child table of this relation.
ParentColumns Gets an array of DataColumn objects that are the parent columns of
this DataRelation.
ParentKeyConstraint Gets the UniqueConstraint that guarantees that values in the parent
column of a DataRelation are unique.
ParentTable Gets the parent DataTable of this DataRelation.
RelationName Gets or sets the name used to retrieve a DataRelation from
the DataRelationCollection.
Example
A DataView provides you with a dynamic view of a single set of data to which you can apply
different sorting and filtering criteria, similar to the view provided by any database
software.
This class provides the following Properties.
Property Description
AllowDelete Gets or sets a value that indicates whether deletes are
allowed.
AllowEdit Gets or sets a value that indicates whether edits are
allowed.
AllowNew Gets or sets a value that indicates whether the new rows
can be added by using the AddNew() method.
RowFilter Gets or sets the expression used to filter which rows are
viewed in the DataView.
Sort Gets or sets the sort column or columns, and sort order
for the DataView.
Example
The following Code creates a view that includes all rows with a null value in the Country field
and then deletes them:
Data Binding
Data binding is the process that establishes a connection between the app UI and the data it
displays. If the binding has the correct settings and the data provides the proper
notifications, when the data changes its value, the elements that are bound to the data
reflect changes automatically.
For example, if the user edits the value in a TextBox element, the underlying data value is
automatically updated to reflect that change.
As the figure shows, data binding is essentially the bridge between your binding target and
your binding source. The figure demonstrates the following fundamental WPF data binding
concepts:
Typically, each binding has four components:
o A binding target object.
o A target property.
o A binding source.
o A path to the value in the binding source to use.
For example, if you bound the content of a TextBox to the Employee.Name property, you
would set up your binding like the following table:
Setting Value
Target TextBox
Target property Text
Source object Employee
Source object value path Name
Example
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.
Step-2: Coding
namespace data_conn
{
public partial class Form2 : Form
{
int r;
SqlConnection cn;
SqlDataAdapter da;
DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
}
cn = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\avadh.mdf;Integrated Security=True;User
Instance=True");
da = new SqlDataAdapter("select * from student", cn);
dt.Clear();
da.Fill(dt);
r = 0;
fatchdata();
dataGridView1.DataSource = dt;
//to add name fields in combobox to search
for (int i = 0; i < dt.Rows.Count; i++)
comboBox1.Items.Add(dt.Rows[i][1].ToString());
}
r = 0;
fatchdata();
label4.Text = (r + 1).ToString() + " OF " + dt.Rows.Count;
}
try
{
da = new SqlDataAdapter("select * from student where name='" + comboBox1.Text + "'", cn);
dt.Clear();
da.Fill(dt);
txtrno.Text = dt.Rows[0][0].ToString();
txtname.Text = dt.Rows[0][1].ToString();
txtcity.Text = dt.Rows[0][2].ToString();
txtcontact.Text = dt.Rows[0][3].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Step-2: Coding
namespace data_conn
{
public partial class Form3 : Form
{
SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\avadhtutor.mdf;Integrated Security=True;User
Instance=True");
cn.Open();
cmd = new SqlCommand("select * from student",cn);
dr = cmd.ExecuteReader();
dr.Read();
fatchdata();
}
private void fatchdata()
{
txtrno.Text = dr.GetValue(0).ToString();
txtname.Text = dr.GetValue(1).ToString();
txtcity.Text = dr.GetValue(2).ToString();
txtcontact.Text = dr.GetValue(3).ToString();
}
{
cmd = new SqlCommand("delete from student where name='"+txtname.Text+"'",cn);
cmd.ExecuteNonQuery();
MessageBox.Show("record deleted");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
catch
{
MessageBox.Show("record not found");
}
}
}
}
Blog
pandyaripal.blogspot.com
instagram
instagram.com/avadhtutor