ADO_NET
ADO_NET
© Copyright by Interviewbit
Contents
Introduction to ADO.NET
ADO.NET is a technology used for data and is provided by the Microso .NET
Framework. It is a part of the .NET framework that supports the communication
between relational and non-relational systems with the help of a set of so ware
components. It supports disconnected architecture using which programmers are
allowed to access data and data services from a database without depending on the
data source.
ADO.NET is comprised of a group of built-in classes that are useful for establishing the
database connection, for gaining access to XML, relational data, and application
data, and for retrieval of a result. It can be used in various programming languages
such as Visual Basic.NET, Visual C++, etc., that are supported by the .NET framework.
Advantages of ADO.NET
ADO.NET has various advantages which can be categorized into the following
categories:
ADO.NET stands for ActiveX Data Object, it is a part of the .NET Framework by
Microso . ADO.NET framework provides a set of classes that are used to handle
data communication with data sources such as XML files and databases (such as
SQL, Oracle, MySQL, MS Access, etc.).
ADO.NET can separate mechanisms for data connectivity, data access, and data
manipulation.
It has introduced the disconnected architecture, in which data can be stored in a
DataSet. ADO.NET has providers for database connection, commands for
execution, and result retrieval.
The ADO.NET classes are stored in the DLL named System.Data.dll .
Various applications like ASP.NET applications, console applications, windows
applications, etc., will use ADO.NET for database connection, command
execution, and retrieval of data.
ADO ADO.NET
Using a single
Using a single connection
connection instance, it is
instance you can send multiple
not possible to send
transactions.
multiple transactions.
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataAdapterExample
{
public partial class DataAdapterDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("data source=.; database=item
{
SqlDataAdapter da = new SqlDataAdapter("Select * from items", conn);
DataSet s = new DataSet();
da.Fill(s);
GridView1.DataSource = s;
GridView1.DataBind();
}
}
}
}
Here, DataAdapter will receive the data from the items table and fill the DataSet,
which will be later used to display the information retrieved from the items database.
Here, data can be converted into Here, We can write our code
XML format. into VB.Net, C#, ASP.Net, etc.
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataSetDemo
{
public partial class DataSetExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("data source=.; database=empl
{
SqlDataAdapter da = new SqlDataAdapter("Select * from employee", conn);
DataSet d = new DataSet();
da.Fill(d);
GridView1.DataSource = d;
GridView1.DataBind();
}
}
}
}
Here, DataSet will be filled by DataAdapter that receives data from the employee
table. This DataSet will be used to display the information received from the
employee database.
DataTable DataSet
DataTable consists of a
DataSet consists of a collection
single database table
of multiple database tables
that is placed within a
which is placed within a memory.
memory.
It represents a collection of
It is a single database
DataTable objects, so there
table, so there will not be
might be a relation between
any relation with other
them to obtain a particular
tables.
result.
In this, DataSource
In this, DataSource objects are
objects are not
serialized.
serialized.
DataSet DataReader
DataReader provides
DataSet provides read/write
read-only access to data,
access to data, so we can
so we can’t update the
update the data.
data.
ExecuteScalar() : This method returns only a single value from the first row
and first column of the ResultSet a er the execution of the query. Even if
ResultSet is having more than one row or column, all those rows and columns
will be ignored. If the ResultSet is empty, it will return NULL.
ExecuteNonQuery() : This method returns the number of rows affected by the
execution of a query. This method is not useful to return the ResultSet.
ExecuteReader() : This method returns an object of DataReader which is a read-
only and forward-only ResultSet. It needs a live connection with the Data
Source. We cannot directly instantiate the DataReader object. A valid
DataReader object can be created with the help of the ExecuteReader() method.
ExecuteXmlReader() : This method builds an object of the XmlReader class and
will return the ResultSet in the form of an XML document. This method is made
available in SQL Server 2000 or later.
Local Transaction:
A local transaction is a single-phase transaction that is directly handled by
the database. Every .NET Framework data provider has its own Transaction
object for bringing out local transactions.
For example, if we want to perform a transaction using SQL Server
database, we import a System.Data.SqlClient namespace. Similarly, to
perform an Oracle transaction, import the System.Data.OracleClient
namespace. A DbTransaction class will be used for writing code that is
independent of the provider and that requires transactions.
Distributed Transaction:
A distributed transaction is coordinated by a transaction monitor and will
make use of fail-safe mechanisms like two-phase commit for transaction
resolution. This transaction will affect multiple resources.
If the user can make use of a distributed transaction, if he wants to do a
transaction across multiple data servers such as Oracle, SQL Server, etc.
If you want a distributed transaction to commit, all participants must
guarantee that data modification made will be permanent. Changes must
remain unchanged even if the system crash or other unforeseen events
occur. Even if a single participant will make this guarantee fail, then the
entire transaction will fail, and updates made to data within the transaction
scope are rolled back.
OLEDB ODBC
An API(Application
Programming Interface) that It is an API for accessing
allows accessing data from DBMS (DataBase
different sources in a uniform Management System).
manner.
It is procedural-based. It is component-based.
resource
odbc_connect(string
datasource , string
username , string password
, [int cursor_type ]) is
OleDbConnection = New used to make a
OleDbConnection(connetionString) connection to an ODBC
is used to make connection with data source. On success,
OLE DB data source. this function will return a
connection resource
handle that is helpful in
accessing the database
using subsequent
commands.
The SQL connection and SQL command object will be created. We pass the SQL
query to the object of the SQL command class. A new data table object will be
created by using the DataTable class and it is filled with data using a data adapter.
Read(): This method reads a record from the SQL Server database.
Close(): It closes a SqlDataReader object.
NextResult(): It moves the data reader to the next result during the time of
batch transactions.
Getxxx(): Various types of Getxxx() methods such as GetBoolean(Int32),
GetChar(Int32), GetFloat(Int32), GetDouble(Int32), etc., are provided by the
DataReader. These methods will read a value of a particular data type from a
column. For example, GetFloat() will return a column value as a Float and
GetChar as a character.
Data Provider: It provides data to all the applications that perform the
database updates. The application can access data through the DataSet or
DataReader object. A data provider is a having group of components such as
Command, Connection, DataReader, and DataAdapter objects. Command and
Connection objects are the necessary components irrespective of the operations
like Insert, Delete, Select, and Update.
Connection: The connection object is needed to connect with the database
such as SQL Server, MySQL, Oracle, etc. To create a connection object, you must
know about where the database is located(Ex: IP address or machine name, etc.)
and the security credentials(Ex: user name and password-based authentication
or windows authentication).
Command: The command object is the component where you will write the SQL
queries. Then by using the command object, execute the queries over the
connection. By using the command object and SQL queries, you will be able to
fetch the data or send the data to the database.
DataReader: DataReader is a connected read-only RecordSet that is helpful in
reading the records in the forward-only mode.
DataAdapter: The DataAdapter acts as a bridge between the dataset and
command object. It receives the data from the command object and puts it into
the data set.
DataSet: The DataSet is a disconnected RecordSet that can be browsed in both
forward and backward directions. We can also update the data using the
dataset. DataSet is filled by using DataAdapter.
DataView Class: A DataView allows you to create various views of data from
DataTable, which can be used for data-binding applications. Using this, you can
display the table with different order of sorting or you can filter the data based
on a filter expression or by row state, etc.
XML: It is possible to create an XML representation of a dataset. In the dataset’s
XML representation, data is represented in XML format and the database
schema is represented in XML Schema Definition(XSD) language.
Disconnected Architecture:
In disconnected architecture, even if the database connection is closed, data
retrieved from the database can be accessed. Disconnected architecture is
based on classes connection, CommandBuilder, DataAdapter, DataSet, and
DataView.
Here, we retrieve and store a recordset from the database so that you can
perform many CRUD (Create, Read, Update, and Delete) operations on the data
within memory, it will be re-synchronized when you reconnect with the
database.
DataSet is a Disconnected Architecture because all records are brought at once
and holding the database connection alive is not necessary.
Here, we create an object of the class SqlConnection and SqlCommand. We pass SQL
Statement to the object of SqlCommand class, which returns a single value. When
ExecuteScalar() function gets executed, a single value will be returned, i.e, the total
salary of employees. This value will be displayed using a message box.
C#
"Server=MSSQL1;Database=Institute;Integrated Security=true;
C#
"Persist Security Info=False;User ID=Harsh;Password=xyz@123;Initial Catalog=Institute;S
A er tables have been added into a DataSet, the below-given code tells about how to
make use of the DataSet tables. If you decide to use the first table in a dataset or to
copy the table data into a data table, then follow the below-given code:
The above code can be used to add the required number of tables in a dataset. This
ensures connection-less access to data. As the dataset is filled with multiple tables,
every time we want to query the data the database connection is not required. It also
makes sure about the reusability of data.
It is not connection-
It is connection-oriented.
oriented.
30. How can you identify whether any changes are made to the
DataSet object since the time it was last loaded?
The DataSet object has two methods to track down the changes:
GetChanges(): It returns the DataSet object that has been changed since it was
loaded or since the execution of the AcceptChanges() method.
HasChanges(): It indicates if any modifications were made since from the time
the DataSet object was loaded or a er a method call to the AcceptChanges() was
made.
Use the RejectChanges() method, if you want to reverse the entire changes since from
the time the DataSet object was loaded.
Using block will be useful in closing the connection automatically. It is not required to
explicitly call the close() method, because using block will do this implicitly when the
code exits the block.
// ConnectionExample.cs
using System;
using System.Data.SqlClient;
namespace ConsoleApplicationExample
{
class ConnectionExample
{
static void Main(string[] args)
{
new Program().ConnectingMethod();
}
public void ConnectingMethod()
{
using (
// Creating Connection
SqlConnection conn = new SqlConnection("data source=.; database=em
)
{
conn.Open();
Console.WriteLine("Connection Has Been Successfully Established.");
}
}
}
}
Output:
Serialization is the method of converting an object into a byte stream which can be
stored as well as transmitted over the network. The advantage of serialization is that
data can be transmitted in a cross-platform environment across the network and also
it can be saved in a storage medium like persistent or non-persistent.
The code for serializing a DataSet is:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.IO;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=data_source_name;Initial Ca
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn); //DataAdapt
DataSet s = new DataSet();
da.Fill(s);
FileStream fObj = new FileStream("C:\\demo.xml", FileMode.Create); // Create
XmlSerializer sObj = new XmlSerializer(typeof(DataSet));
sObj.Serialize(fObj, s); //Serialization of a DataSet
fObj.Close();
}
}
In the above given example, the database name is employee and, the table name is
emp. The data in a DataSet will be serialized and stored in a demo.xml file by using
Serialize() method.
35. Give an example code to fill the GridView by using the object
of DataTable during runtime.
using System;
using System.Data;
Output:
Conclusion
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions