Professional Documents
Culture Documents
System.Data
System.Data.SQLClient
System.Data.OleDb
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.
Answer: The following are some of the most important components of ADO.NET data
providers:
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.
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);
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.
dataTable.Rows.Add (newOrder);
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.
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 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.
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.
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
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
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.
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.
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