jump to navigation

Connecting to an Access DataBase with ADO.NET December 6, 2005

Posted by Christian López Espínola in CSharp, Programming.
trackback

This is a simple guide for reading data from a database. I chose Access for the example, but using another Database Manager is very similar to this.

At first, we have to connect to the database, using its connection string, and open the connection:

OleDbConnection con;
con = new OleDbConnection();
con.ConnectionString = @�Provider=Microsoft.Jet.OLEDB.4.0;� +
@�Data source= C:\cd.mdb�;
con.Open();

Now we create the command. For this we use OleDbCommand. Its constructor receives as parameters one string with the SQL sentence and the connection object.

OleDbCommand cmd;
cmd = new OleDbCommand(“select * from Customers”, con);

For sentences that read data, we have to use the method ExecuteReader. Its result rows are saved in an object called DataReader.

OleDbDataReader dr;
dr = cmd.ExecuteReader();

Now we iterate over the reader and print data at console. For this we use a DataReader indexer, which parameter is the name of the column.

while (dr.Read())
{

Console.WriteLine(“Name: ” + dr["Name"].ToString();
Console.WriteLine(“Name: ” + dr["Phone"].ToString();
Console.WriteLine(“Name: ” + dr["Mail"].ToString();

}

Closing all opened connections is very important:

con.Close();

Writing good code is important. For writing good code, we should take care about exceptions methods can throw. In this little demo we don’t make it, but be careful in your applications.

Comments»

1. stalker - December 6, 2005

I would like to believe that you are who writes these articles and not Mr. Copy-n-Paste.

I’m not a bit crazy man… I was just kidding…

Anyways, good luck with your blog!! Keep up the good work.

2. penyaskito - December 6, 2005

I would like to believe you’re joking, ‘cos you can search in google and if you find the origin of the article in another page, I’ll return you your money!

Bad motherfucker, Mr.Stalker (I just have seen Pulp Fiction).

3. Coquevas - December 7, 2005

The Wolf: Well, let’s not start sucking each other’s dicks just yet.

4. anony - May 25, 2006

@‿Provider=Microsoft.Jet.OLEDB.4.0;‿ +
@‿Data source= C:\cd.mdb‿;

This is not clear
can u plz expalin this….