Mohamed Mansour's Personal Website
Articles
Connect to Access Database in C#
Posted on June 14, 2006, 1:58 am EST
Hi, some people have asked me how to access a database within C# ( C Sharp ). So here it is. The example was tested on Visual Studio 2005. It will work fine on other versions (like 7)
Here I will use the Connection Object and the Command object. I will use ADODataReader object which will hold the RecordSet which is dependent upon the query. Please not that this is taken out from a snippet of a pattern that I constructed in one of my projects.
Here are the namespaces we need to use.
CODE:
using System.Data.OleDb;
using System.Data;
Here is the wonderfull compact code :)
CODE:
try
{
// Initializations
string FirstName = ""; // Using it to store the db fname
string database = "PersonDatabase.mdb";
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + database;
// Prepare the connection
OleDbConnection dbConnection = new OleDbConnection(connectionString);
// The select query that I will be using
string query = "SELECT FirstName FROM PersonTable WHERE PersonID = 1";
// Prepare the Command Object to execute the query
OleDbCommand command = new OleDbCommand(query, dbConnection);
// Now lets open the connection
dbConnection.Open();
// Lets bind it to a ADO.NET DataReader which will be like a result set
OleDbDataReader reader = command.ExecuteReader();
// Lets read one row
if (reader.Read()) // True a row exists
// Lets store that column to firstname var
FirstName = reader.GetString(0).ToString();
else // Returned nothing
FirstName = "Empty";
// Close the connection
dbConnection.Close();
// Echo out the Firstname
Console.WriteLine(FirstName);
}
catch (Exception e)
{
return e.ToString();
}
What I am trying to do is connecting to the ACCESS Database. I introduced a DataReader Object to be like a ResultSet object.
Once my ADO.NET Database Package is completed, I will release it. It is a api that I made that does an abstraction of DBMS to use. But the example that I showed in this blog connects to the database and gets the name of the person who's id is 1. I hope you understood the code, if you have any problems ... Leave a comment :)
