You are on page 1of 16

Basic ADO.

NET Interview Questions


June 5, 2014 by usman_malik Leave a Comment

ADO.NET is Microsofts latest technology


for manipulating and access data objects either in the form of a databases such SQL
Server, Oracle or Access, or general data sources such as text files, XML files and other
file streams. Anyone looking to pursue a career in Microsofts application development
technologies, mainly .NET, must have some experience and knowledge in ADO.NET.
This article contains some of the most fundamental and frequently asked questions in any
.NET-related job.
For more detailed C# ADO.NET tutorials, look at this Udemy.com course.
Q1: What is ADO.NET?
Answer: ADO.NET stands for ActiveX Data Objects and is used to access and
manipulate data services in Microsoft applications. ADO.NET interacts with data using
a disconnected data set model and is mostly used for accessing relational databases.
Q2: What are some of the namespaces in ADO.NET that provide access to data?
Answer: There are three major namespaces used for interacting with data in ADO.NET

System.Data
System.Data.SQLClient
System.Data.OleDb

Q3: What is DataSet Object in ADO.NET?


Answer: The DataSet object is an in-memory representation of a data sources such as
table records from a database. The DataSet object stores data in the form of rows and
columns where each row represents a record and each column represent a particular value
or property from that record.

Q4: What is an ADO.NET DataReader?


Answer: The DataReader object in ADO.NET is used to sequentially read data from an
underlying data source. The DataReader object provides read-only access to data and
cannot be used for DDL and DML operations.
Q5: What is LINQ?
Answer: LINQ stands for (Language Integrated Query) used for querying collections of
data. LINQ queries can be executed on local collections such as types from
System.Collections namespace and System.Collections.Generic namespace. LINQ
queries can also be executed over LINQ to SQL and Entity framework classes that are
used to interact with databases and other data sources that do not exist within the
application domain, such as XML.
Q6: What is Object Pooling in ADO.NET?
Answer: In .NET, whenever functionality has to be performed, the Class that contains
that functionality is instantiated. The object of the class is created, desired functionality is
performed and then that object is destroyed. This process of creating and destroying
objects is expensive. In ADO.NET objects are consistently created and destroyed as the
application is connected to database, fetches records from database and disconnects from
database. Therefore, the objects that are frequently used are placed in a pool from where
they can be accessed whenever a related functionality needs to be performed. This
phenomenon is known as object pooling.
Interested in learning more about ADO.NET with C#? Take this Udemy.com course
Q7: What is ADO.NET DataAdapter?
Answer: To perform communication between ADO.NET data sources such as databases
and XML files and a DataSet, the DataAdapter object is used. All CRUD (create, read,
update and delete) queries are performed using this DataAdapter.
Q8: Briefly mention some of the benefits of ADO.NET data access technology.
Answer: The following are some of the important benefits of using ADO.NET for data
access:

ADO.NET objects are highly programmable and are flexible enough to be


tweaked and twisted to achieve the desired functionality.
Code written in ADO.NET is highly maintainable and new data access features
can be added to existing application imperceptibly.
ADO.NET objects are simple .NET objects that translate into MSIL code.
Therefore, ADO.NET code written in one language can be seamlessly used with
other .NET languages as well.

ADO.NET supports data scalability and is independent of the amount of data


stored in the underlying database. Therefore, if data source expands or shrinks, the
impact on the ADO.NET classes is minimal.

Q9: Differentiate between Boxing and Unboxing


Answer: The process of storing a value type into a reference type variable or object is
known as boxing. Unboxing is the opposite of boxing and is referred to as the process of
storing a reference type into a value type variable. In .NET, boxing is done implicitly,
while a casting mechanism is required to achieve unboxing.
Q10: Do ADO.NET supports stored procedures?
Answer: Yes, ADO.NET contains a complete framework for executing stored procedures
on a data set. Stored procedures in ADO.NET are used mostly for common repetitive
functions.
Q11: What are the basic layers of any ADO.NET based data-centric application?
Answer: Every data-centric application that uses ADO.NET should ideally be structured
into three layers.

Presentation layer: Provides all the GUI and interaction services to end user.
Business Logic Layer: Used to implement all the business logic of an application.
Data Access Layer: Provides types that are used to interact with the underlying
databases.

Q12: Elaborate on some of the advantages of using stored procedures in ADO.NET.


Answer: The following are some of the benefits of implementing ADO.NET stored
procedures:

Stored procedures reside in databases in compiled form. This results in extremely


fast performance.
Stored procedures require less network traffic and bandwidth to execute on
remote databases since they do not contain any extra information but only
compiled data.
Stored procedures are secure and invulnerable to any outside threat data might
result in loss or leakage of data.

Q13: Can data be edited in a repeater control?


Answer: No, the repeater data control is used to show data. Data cannot be edited in a
repeater control. The DataGridView controls can be used for editing purposes.
Q14: Briefly explain some of the components of ADO.NET Data providers:

Answer: The following are some of the most important components of ADO.NET data
providers:

Connection: This is the object responsible for establishing a connection to the


database.
Command: The object responsible for executing commands and stored
procedures.
ExecuteReader: Returns a complete set of results
ExecuteScaler: Returns only a single value
ExecuteNonQuery: Execute a command on a database but it doesnt return any
value from the database. Used mostly for insertion and update.
DataReader: Provides read-only and forward-only access to a database.

This article contains some of the most fundamental and basic ADO.NET questions that
can be asked in any .NET job interview. To study how ADO.NET can be used to develop
data-centric applications, see this course.

ADO.NET Tutorial for Beginners


June 2, 2014 by usman_malik Leave a Comment

ADO.NET, an important feature of the


.NET framework, is a set of object-oriented libraries used to provide consistent access to
data sources such Microsoft SQL server, Access, text files, Excel spreadsheets and XML.
ADO.NET classes reside in a namespace System.Data and its implementation with
XML is in System.Xml. Most of the data-centric applications use the ADO.NET to
connect to their data sources and retrieve, manage and update the data. This ADO.NET
tutorial covers a basic introduction of two main components of ADO.NET classes, which
are .NET framework Data Providers (for connecting to database, executing commands,
retrieve results, etc.) and DataSet (disconnected cached data).
New to C#? Check out a Udemy.com course.

ADO.NET .NET Framework Data Providers


For connecting to the different data sources and interacting with data, a relatively
common managed interface is available in ADO.NET data provider model. A single set of
classes is not able to accomplish access to all of the data sources since each of a data
source has special interface, exposed to a separate protocol and require a different set of
rules to connect and interact.
Following are the four core objects of ADO.NET data providers.

The Connection object, which establishes the connection to a data source.


The Command object, which interacts with the data source by executing
commands. It uses the Connection object to identify the data source.
The DataReader object reads a stream of data from data source with a read-only
attribute. This object retrieves the result of SELECT statement from a
Command object.
The DataAdapter object fills the DataSet with requested part of data source as
a discontinued data and manages the updates with the data source.

The following are the main data providers available in .NET.

SQL data provider is for accessing the Microsoft SQL Server where no
intermediate layers of service components are involved. These classes are located
in System.Data.SqlClient namespace.
OLE DB data provider is for Access and Excel as they expose an OLE DB
interface. Classes are located in System.Data.OleDb namespace.
ODBC data provider classes reside in System.Data.Odbc namespace used for
old databases exposing the ODBC interface.
Oracle data provider is used for interacting with Oracle data sources through
Oracle client connectivity software. Classes are encapsulated in
System.Data.OracleClient namespace.

The following C# code snippet demonstrates the use of OLE DB data provider classes to
read Excel spreadsheet.
string connectionString = string.Format
("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended
Properties=\"Excel 12.0 Xml; HDR=No; IMEX=1; MAXSCANROWS=20;
READONLY=TRUE\";", strExcelFilePath);
OleDbConnection connection = new OleDbConnection (connectionString);
try {
connection.Open ();
OleDbCommand command = new OleDbCommand ("select * from [SheetName$]",
connection);

OleDbDataAdapter dataAdapter = new OleDbDataAdapter (command);


DataSet dataSet = new DataSet ();
dataAdapter.Fill (dataSet);
con.Close ();
}
catch (Exception e) {
}
finally {
con.Close ();
}

In the above code, ACE OLEDB driver is used to connect to an Excel spreadsheet using
OledbConnection object with a connectionString (the path of a data source, properties
for file access and name of a provider) as an argument. The OledbCommand object uses
that connection object and a query string to set a command for a data source. Finally, the
OledbDataAdapter object takes that command object as an argument and retrieves all
the data of a sheetName in query string and filled a DataSet with that data.
Interested in learning more about ADO.NET? Look at this online course at Udemy.com.
ADO.NET DataSet
The ADO.NET DataSet object supports the disconnected data access and operations on
the data. It is cached data that provides a reliable relational programming model
regardless of the data source. Therefore, it can be used with different data sources such as
XML data or for managing the part of data downloaded in an application to increase the
scalability ability of an application.
ADO.NET DataSet contains DataTableCollection and DataRelationCollection object.
A DataTableCollection have none or multiple DataTable, which represents a single
table, residing in the memory. A DataTable contains DataColumnCollection, a
collection of columns, and ConstraintCollection, a collection of constraints, which
collectively describes the schema of the table. It also contains DataRowCollection, a
collection of rows, which holds the data in the table in the form of DataRow objects, a
row of data in a table. A DataRelationCollection have none or multiple DataRelation
objects, which represents a relationship between rows of two DataTable object by
identifying the matched columns in these two tables.
The following C# code snippet illustrates the basic use of ADO.NET DataSet and
Microsoft SQL Server data provider classes, to access the SQL server, retrieve and filter
the Customer data.

string connectionString = @"Data Source=SQLSERVERXXXX; Initial


Catalog=DB_NAME; User ID=USER_NAME; Password=USER_PASSWORD";
SqlConnection conenction = new SqlConnection (connectionString);
DataSet dataSet = new DataSet ();
SqlCommand command = new SqlCommand ();
command.Connection = conenction;
SqlDataAdapter dataAdapter = new SqlDataAdapter ();
command.CommandText = "Select * From CustomerOrder";
dataAdapter.SelectCommand = command;
dataAdapter.Fill (dataSet, "CustomerOrder");
DataTable dataTable = new DataTable ();
dataTable = dataSet.Tables[0];
if (dataSet.Tables.Count > 0)
{
foreach (DataRow dataRow in dataTable.Rows)
{//Traverse all rows and output when a order status is only production
if (dataRow["Order_Status"].ToString () == "Production")
{
Console.WriteLine ("ID: " + Convert.ToString (dataRow["Customer_ID"]));
Console.WriteLine ("Name: " + Convert.ToString
(dataRow["Customer_Name"]));
}
}
}
DataRow newOrder;
newOrder = dataTable.NewRow ();
newOrder["Customer_ID"] = 04;
newOrder["Customer_Name"] = "Mr. George";
newOrder["Order_Status"] = "Delivered";
//Add a row

dataTable.Rows.Add (newOrder);

newOrder = dataTable.Rows.Find (1);


//Edit a row
newOrder.BeginEdit ();
newOrder["Order_Status"] = "Delivered";
newOrder.EndEdit ();

newOrder = dataTable.Rows.Find (1);


//Delete a row
newOrder.Delete ();

SqlCommandBuilder CommandBuilder = new SqlCommandBuilder (dataAdapter);


dataAdapter.Update (dataSet, "CustomerOrder");

In the above code snippet, an ADO.NET DataSet connection is established with the SQL
server database. Using SqlCommand and SqlDataAdapter, all data specified in
SELECT query is retrieved and DataSet object is filled with it. A DataTable at index
zero of DataTableCollection holds the entire customers data. A DataTable object is then
enumerated using a foreach loop to get a row of a table in DataRow object in
iterations. To insert a new row, first a NewRow method of DataTable is called to return
a DataRow object with the same fields as in the other DataRow objects of DataTable.
Then the Add method of DataTable.Row adds a new row in DataTable. To update and
delete a row, the Find method of DataTable.Row is called that searches for a record,
provided the value matches the primary key of a table. When a match is found,
BeginEdit and EndEdit methods are called to update the retrieved record. The Delete
method is used to delete that searched record from a DataTable. Finally, all changes are
made to a database table in SQL server by calling the Update method of DataAdapter.

SQL Tutorial: Understanding Your


Database Language
May 14, 2014 by Jennifer Marsh Leave a Comment

Most database use Structured Query


Language (SQL). This language interfaces between you and your database tables. Even if
you know another web-based scripting language (C#, PHP or VB.NET), youll need to
know how to query data from your database. MySQL, Microsoft SQL Server and Oracle
use similar language structures. While they are similar, they have some differences, but
learning one language will help you understand the rest of them.
New to SQL? Learn how to work with the language at Udemy.com
A Basic Query to Retrieve Data
The select statement is the main phrase for retrieve data. No data is changed or deleted.
Its just retrieved for your use. You can display the data on a web page or use it to update
data later on in your program. The following code is an example of a select statement:
select * from users
The above statement is probably the most basic SQL statement you can write. The
statement basically says select all records from the users table. The asterisk tells the
database to return all columns. For instance, the users table could have first and last
name, address and signup date columns. With the above statement, youd see them all.
Obviously, you want to filter your records. You usually want to retrieve only a certain
record set. For instance, a customer logs in to your website. You then retrieve the
customers information based on the customers ID (userid in this example). The
following code retrieves a user with an ID of 3:

select * from users where userid=3

In addition to retrieving a filtered record set, you should also limit the number of columns
returned. The asterisk returns all columns. This includes signup dates, modified dates,
foreign keys and other useless information for a front-end web page. You can specify the
columns returned. You should only return columns you need to work with on the frontend. The following statement selects only the first and last name columns:
select first_name, last_name from users where userid=3

There are several other types of select statement. To learn more about the SQL language,
take a course at Udemy.com.
The Update Statement
The update statement is what you use to edit records. Most of your tables wont stay
static. Youll need to change the data. The update statement is how its done. The
following code is an example of a basic update statement:
update users set first_name=Jane where userid=3

An important part of this statement is the where clause. If you forget it, youll update
every record in the users table to Jane. You must ensure you include a where clause in
your update statements unless you want to change every record (and you usually dont).
You can change multiple columns at a time as well. The following code changes the first
and last names for the user with an ID of 3:
update users set first_name=Jane, last_name=Smith where userid=3

The Delete Statement


The SQL delete statement removes records from a table. Again, the where clause is
important in this statement as well. Without the where clause, youll delete every record
in your table. As with the update statement, this type of mistake is disastrous and it means
youll need to restore data from a backup.
The following code is an example of a delete statement:
delete from users where userid=3

The above code just deletes one record, but you can use the where clause to delete
multiple records at a time. You should probably limit the amount of delete statements
you execute. Its standard to set records as active or inactive instead of just deleting them.
You add a bit column to the table and deactivate when necessary, but you still have a
record of the account, order or other type of record.

Most SQL databases are relational. This means that tables are linked together using
primary and foreign keys. For instance, a customer ID is stored to each order record to
link customers with orders. This means that you need to delete the order before you
delete the customer. If you dont, it leaves what is called orphaned records. Aside from
the problems with deleting records, orphaned records can cause bugs in your system.
The Insert Statement
The insert statement is how you add a record to the database table. The insert statements
length is dependent on the data required to create a record and any default values set in
the tables column declarations. For instance, if you dont allow nulls for a users first and
last name, then you must include the first and last name statement in your insert
statement. The alternative to this limitation is setting a default value in the table
definition. Youll set these values when you define your tables.
The following code is an example of an insert statement:
insert into users (first_name, last_name) values (Jane, Smith)

The above statement adds one record. The value Jane and Smith are used for the first
and last name.
This statement will throw an error if you dont include all necessary data. For instance,
most user tables have an ID column. You dont calculate this unique ID, but the database
can be set to auto-increment the column by 1 each time a new record is inserted. If the
column does not increment, an error returns. These columns are also set as primary keys
by some database administrators. Primary keys must be unique and cannot be null, so you
must account for this issue when inserting new data.
You can also insert some default data. For instance, you should have a Create Date in
your database. In MSSQL, you can use the following statement to insert a record with the
default system date using the getDate() function:
insert into users (first_name, last_name, create_date) values (Jane,
Smith, getdate())

These are the four basic SQL statements youll need as you work with a SQL database.
More complex statements exist, but you wont need them for most operations.

SQL UNION vs UNION ALL


Similarities and Differences
April 9, 2014 by Arpita Bhattacharjee Leave a Comment

Which operator do you use if you have to


combine the result sets of two or more queries and display all the rows returned by each
of the queries as one single result set? The solution is to use the UNION set operator.
Except in MySQl, the set operators UNION and UNION ALL are supported by most
database platforms like DB2, Oracle, SQL server, and Postgre SQL.
When using UNION remember that the order, number, and datatype of columns should
be the same in all queries. The datatypes need not be identical, but they should be
compatible. For example, CHAR and VARCHAR are compatible datatypes. If you want
to recollect information on tables, SQL database operations, and programming then SQL
Database for Beginners and Learn SQL in 6 days are great refresher courses. If you need
further guidance on writing SQL queries and learning how to build applications or
generate business reports, then refer Introduction to SQL Training.

Comparison Between UNION and UNION ALL


UNION
The UNION command is used to select related information from two tables, much like
the JOIN command. With UNION, only distinct values are selected by default. A UNION
statement effectively does a SELECT DISTINCT on the result set.
UNION Statement in SQL Server
The UNION operator is used to combine the result set of two or more SELECT
statements.

Here are some of the simple rules of using UNION in SQL:

Each SELECT statement within the UNION must have the same number of
columns and the columns must have similar or compatible data types.
The columns in each SELECT statement must be in the same order.
If the columns sizes of the two tables vary, then while returning data, SQL server
uses the larger of the two columns. Thus if a SELECT.UNION statement has a
CHAR (5) and CHAR (10) column, then it will display output data of both the
columns as a CHAR (10) column.
If the columns across the table have different column names then in general, the
column names of the first query are used.

SQL UNION Syntax


SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL
The UNION ALL command is similar to the UNION command, except that UNION ALL
selects all values. So with UNION ALL duplicate rows are not eliminated, rather they are
included. This operator just pulls all rows from all tables which satisfy the query and
combines them into a table. If you are sure that all the records returned from a UNION
operation are unique, then using UNION ALL is a better option as it gives faster results.
The results from a UNION ALL are unsorted. So after getting the results, you can sort
them by using the ORDER BY clause. A ORDER BY should be inserted with the last
SELECT statement.
SQL UNION ALL Syntax

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

Example
To compare UNION and UNION ALL let us take the following table Contacts
containing columns for City, State, and Zip.
City

State

Zip

Nashville

TN

37235

Lawrence

KS

66049

Corvallis

OR

97333

UNION ALL SQL Statement


If we apply UNION ALL SQL statement, then we will combine the two queries which
will retrieve and combine records from Tennessee (TN) twice.
Syntax:
SELECT City, State, Zip FROM Contacts WHERE State IN (KS, TN)
UNION ALL
SELECT City, State, Zip FROM Contacts WHERE IN (OR TN)
Result of UNION ALL syntax:
City

State
Nashville

Zip
TN

37235

Lawrence

KS

66049

Nashville

TN

37235

Corvallis

OR

97333

With UNION ALL syntax the TN record appears twice, since both the SELECT
statements retrieve TN records.

UNION SQL Statement


We now use the SQL UNION command by writing the syntax:
SELECT City, State, Zip FROM Contacts WHERE State IN (KS, TN)
UNION
SELECT City, State, Zip FROM Contacts WHERE IN (OR TN)
The result of the UNION query will be as follows:

City

State
Corvallis

Lawrence
Nashville

KS
TN

Zip
OR

97333
66049
37235

Notice that the TN record appears only once, even though both the SELECT statements
retrieve TN records. The UNION syntax automatically eliminates the duplicate records
between the two SQL statements and also sorts the results. The resultant displayed
records are sorted alphabetically and so the Corvallis record appears first even though it
is from the second SELECT statement. A GROUP BY clause can be added at the end to
sort the list.
A UNION query, by definition, eliminates all duplicate rows and compared to UNION
ALL it is slower as it does a sorting operation. To do this in SQL Server, a UNION
statement must build a temporary index on all the columns returned by both queries. If
the index cannot be build for the queries, then you will get a SQL error. In such cases it is
best to use the UNION ALL statement.

Application in Other Database Severs


In Oracle
Oracle does not support UNION or UNION ALL on queries under these circumstances:

Queries containing columns of LONG, BLOB, CLOB, BFILE, or VARRAY


datatype.
Queries containing a FOR UPDATE clause or a TABLE collection expression.

In DB2
In DB2 database system, you can use both UNION and UNION ALL along with the
VALUES clause.

Conclusion
If you remember the simple rules to use UNION and UNION ALL and the syntax for the
same, then combining tables as per your requirement becomes an easy task. If you want
to explore basic SQL queries and other code statements, then it is a good idea to check
out SQL Queries 101. If you want to gather knowledge on Oracle SQL and Oracle
PL/SQL Programming then it may be worth to peek into Introduction to Oracle SQL, or

You might also like