Accessing Database
Accessing Database
Accessing Database
Database Concepts
Database is the media to store data. If you have an application that has to store and retrieve data,
your application must be using a database.
A File is the simplest form of saving the data in the disk, but is not the most efficient way of
managing application data. A database is basically a collection of one or more files, but in a
custom format, and data is organized in a specific format such a way that it can be retrieved and
stored very efficiently.
Some examples for databases are :
MS Access
SQL Server
Oracle
MS Access is a very light weight database provided by Microsoft for applications with less
number of users and relatively small quantity of data. MS Access saves data into database files
with the extension .mdb. Usually, MS Access comes along with MS Office package. If you
already have the .mdb database file, you can freely use it with your application and you do not
need MS Access software. The MS Access software is required only if you want to directly open
the database and manipulate the data or change the database schema.
SQL Server (Microsoft product) and Oracle (Oracle Corp.) are more complex, advanced,
relational databases and they are much more expensive. It can support large number of users and
very high quantity of data. If you are developing a software, which might be accessed
simulatenously by 100s of users or if you expect your data may grow 100s of MBs, you might
consider one of these. (We are learning Microsoft .NET.. so you might want to consider the SQL
Server than Oracle, for which Microsoft provides special data access components!!)
In this tutorial, we will be using only MS Access for simplicity. Most of the samples provided in
this site uses MS Access database for simplicity and easy download.
ADO.NET
ADO.NET is the data access model that comes with the .NET Framework. ADO.NET provides
the classes required to communicate with any database source (including Oracle, Sybase,
Microsoft Access, Xml, and even text files).
Description
SqlClient
Objects
OleDb Objects
OleDbConnection
Command
OleDbCommand
OleDbDataReader
SqlDataAdapter OleDbDataAdapter
Each provider may have classes equivalent to above objects. The name of the classes vary
slightly to represent the provider type appropriately.
Depending on the type of database you work on, you will have to choose either OleDb or
SqlClient (or, some other provider) objects. Since all our samples use MS Access database, we
will be using OleDb objects in all the samples. If you like to use SqlServer, you just need to
replace the OleDb objects with the equivalent SqlClient objects.
We can use the DataAdapter or DataReader to populate data in DataSet. Once we populate data
from database, we can loop through all Tables in the DataSet and through each record in each
Table.
On the first look, this may look bit confusing, but once you understand the concept and get
familiar with the Ado.NET classes, you will appreciate the power and flexibility of Ado.NET.
Soon, we will publish several ADO.NET samples here. Please check back soon.
Let us analyze the code. First we have declared a connection string. The connection string points
to an MS Access database. Before you execute this code, make sure you have the database in the
path specified. Or, change the path accordingly.
In the next step, we are creating a OleDbConnectionobject and passing the connection string
to this object. The line 'myConnection.Open();' will open a connection to the MS Access
database specified in the connection string. If the database doesn't exists or if it is not able to
open a connection for some other reason, the '.Open' call will fail.
Next step is, creating a OleDbCommand object. This command object is used to execute sql
statements and uses the connection opened by the OleDbConnection object.
Note that before executing a command, we have to establish a valid connection to the database.
And finally, after we have executed with the command, we will close the connection.
The above sample code executes a sql statement and returns no data from database. We are
calling the method 'ExecuteNonQuery()' on the command object. If we have a 'select ...'
statement which returns data from database, we cannot use the 'ExecuteNonQuery()' method.
The following sample demonstrates using OleDbDataAdapterObject and DataSet to
retrieve data from databbase.
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\\Samples\\Employee.mdb";
OleDbConnection myConnection = new OleDbConnection( connectionString );
string query = "select * from EMPLOYEE_TABLE";
OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
DataSet employeeData = new DataSet();
myAdapter.Fill ( employeeData );
Here we are creating a OleDbConnection object and we are just passing the object to the
OleDbDataAdapterobject. Also, we pass the 'select ...' query to the OleDbDataAdapter.
Next, we call the '.Fill()' method of the OleDbDataAdapter. This step will populate the
dataset ( called 'employeeData' ) with the data retrieved for the sql statement 'select * from
EMPLOYEE'.
As you already know, a DataSet can contain a collection of tables. But in our case, our sql
statement will retrieve data from only one table. So, our DataSet will have only one table.
We can iterate through the table in the dataset and retrieve all the records. See the following code
demonstrating this:
Here we are creating a OleDbConnection object and we are just passing the object to the
OleDbDataAdapterobject. Also, we pass the 'select ...' query to the OleDbDataAdapter.
Next, we call the '.Fill()' method of the OleDbDataAdapter. This step will populate the
dataset ( called 'employeeData' ) with the data retrieved for the sql statement 'select * from
EMPLOYEE'.
As you already know, a DataSet can contain a collection of tables. But in the above case, our sql
statement will retrieve data from only one table. So, our DataSet will have only one table.
Commonly used properties and methods of DataSet
Property : Tables
The Tables propertly allows us to retrieve the tables contained in the DataSet. This property
returns a DataTableCollection object. The following sample code demonstrates iterating
through the collection of tables in a data set and print the name of all the tables.
Or, you can use the indexer to access any specific table in the collection.
Method : GetXml()
The GetXml() method returns the XML representation of the data from the DataSet.
Method : WriteXml(...)
The WriteXml() method allows to save XML representation of the data from the DataSet to an
XML file. There are many overloaded method available, which takes various parameters. The
example shown below takes a file name as parameter and saves the data in DataSet into xml
format to the file name specified as parameter. We can optionally save only the data or both data
and schema.
Method : ReadXml(...)
The ReadXml() method allows to load the DataSet from an XML representation of the data.
There are many overloaded method available, which takes various parameters. The example
shown below takes a file name as parameter and loads the data from XML file into the DataSet.
This method can be used to load either the data only or both data and schema from the XML.
There is another method called 'ReadXmlSchema()', which can be used to load only the schema
from a file.
The methods WriteXml() and ReadXml() are useful to save the data from a database into some
temporary files, transport to other places or keep it as a local file and load later. Many
applications, including the SpiderAlerts tool available for download from this site, uses DataSet
to manipulate data and saves/retrieves them from local disk using the WriteXml() and
ReadXml() methods.
The SpiderAlerts tool communicates with webservices in our site and retrieves the alerts in the
form of a DataSet. Once the Alerts are retrieved, it is saved into local computer using the
WriteXml method. (This implementation may be changed soon in the future versions of this tool.
We are considering saving(serializing) the DataSet into Isolated Storage (IsolatedStorage is a
new feature part of the .NET Framework - it is a kind of hidden file system).
You can read more about Isolated Storage here:
http://www.dotnetspider.com/Article18.aspx
http://www.dotnetspider.com/kb/Article344.aspx
The source code for the SpiderAlerts tool will be available in this site's projects section soon.
The following sample code explains these steps. This sample code retrieves data from an MS
Access database.
row["EmployeeNumber"].ToString() );
MessageBox.Show( "Name : " + row["Name"].ToString() );
MessageBox.Show( "Address : " + row["Address"].ToString() );
}
}