Click here to Skip to main content
Click here to Skip to main content

OLE DB - First steps

By , 1 Dec 2001
 

Introduction

This article intends to introduce you to using OLE DB for database access. It does this by showing you how to use OLE DB to insert records into a database and then read back those records. Before you start there are some things you need to do first, like creating an MDB file.

Things to do first...

  • First create a new MS Access database called test.mdb and create a single table and call it 'main'.
  • Now add two fields to 'main' called 'Name' of type 'Text' and 'Age' of type 'Number'.
  • Copy test.mdb to d:\

Some concepts

In .NET, connections to databases and queries are achieved through data providers. The OLE DB .NET data provider is implemented through various classes within the System::Data::OleDb namespace. In this article we only examine three of these classes - OleDbConnection, OleDbCommand and OleDbDataReader. The OleDbConnection object represents a database connection. The OleDbCommand object wraps an SQL command that is performed on a database connection.  When we are making an INSERT or an UPDATE query on a database table, those two are the only classes we'll need. But when we are retrieving data from a table, we'll also need to use the OleDbDataReader class. This class allows us to browse through a row of records in a forward-only direction.

Inserting records code snippet

//Create the OleDbConnection object 
//and associate it with our database
OleDbConnection* conn = new OleDbConnection(
    "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=d:\\test.mdb");

//Open the database connection
conn->Open();

//Create an OleDbCommand object and
//pass it the SQL command and the OleDbConnection
//object to use to connect to the database
OleDbCommand* cmd = new OleDbCommand(sqlstr,conn);

//Execute the SQL command
cmd->ExecuteNonQuery();

//Close the connection to the database
conn->Close();

Inserting records is the simpler of the two processes. We create a connection using the OleDbConnection object, create an OleDbCommand object and associate it with the OleDbConnection object. Now we call the ExecuteNonQuery method, which will execute the SQL command we had passed to the OleDbCommand  constructor. We then close the connection.

Reading records code snippet

//Create the OleDbConnection object 
//and associate it with our database
OleDbConnection* conn = new OleDbConnection(
    "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=d:\\test.mdb");

//Open the database connection
conn->Open();

//Create an OleDbCommand object and
//pass it the SQL read query and the connection to use
OleDbCommand* cmd = new OleDbCommand(sqlstr,conn);

//Procure the OleDbDataReader object to browse the recordset 
OleDbDataReader* rdr = cmd->ExecuteReader();

//Keep reading records in the forward direction
while (rdr->Read())
{
   //Use one of the various methods available to read the data
   //Eg:- GetValue, GetValues, Item etc.
    . . .
    . . .    
}

//Close the connection to the database
conn->Close();

This is basically the same as far as creating the OleDbConnection and OleDbCommand  objects are concerned. But instead of calling ExecuteNonQuery directly, we call ExecuteReader which will return a OleDbDataReader object. We can use this OleDbDataReader object to browse through the recordset. Keep calling Read which will return false when it has finished the whole recordset. There are several ways to read from a recordset but I prefer get_Item which allows you to specify a field name opposed to other functions like GetValue which require us to pass the index of the field in the table which is a bad method in my opinion.

Console::WriteLine(rdr->get_Item("FullName"));

There is a sequel to this article on the use of bound controls with OLE DB which you can find here.

Revision History

  • Jul 04 2002 - Did a full redo of the article, added a sample project and now uses MC++ instead of C#
  • Dec 02 2001 - Changed the program for .Net beta 2.0

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nish Sivakumar
United States United States
Member
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhow do i pass the arguments to the smemberAnonymous12 Jun '02 - 6:32 
how do i pass the arguments to s i tryed this maybe you could help me out i cant get it to accept input to the array to add to the DB im new to programming so maybe you could help me out?
 
using System.Data.OleDb;
using System;
 
class nish
{
public static void Main(string[] s)
{

Console.WriteLine("Enter the name please");
s[0] = Console.ReadLine();
Console.WriteLine("Enter the Age now please");
s[1] = Console.ReadLine();
//check and see if they have entered the two arguments
//if they have then proceed
if(s.Length==2)
{
//create the OleDb connection object
OleDbConnection conn=new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
 
//Open the OleDb connection
conn.Open();

//Declare a command object so we can issue SQL commands to the connection
OleDbCommand cmd;
 
//Create the SQL using the command line arguments
string sql="insert into table1 values('" + s[0] + "','" +s[1]+"')";
 
//construct the command object passing the SQL and the connection object as parameters
cmd=new OleDbCommand(sql,conn);

//Now execute the SQL
cmd.ExecuteNonQuery();
 
//Close the connection
conn.Close();
}
else //if they have entered less than 2 arguments or more than 2 arguments
//show the following error messageam
{
Console.WriteLine("Wrong number of arguments!");
Console.WriteLine("Use :- dbinsert [name] [age]");
}

}

}

AnswerRe: how do i pass the arguments to the smemberNish - Native CPian12 Jun '02 - 14:15 
You are not doing it right.
 
static void Main(string[] s)
 

Here s is NOT a string array that you can use. s is the list of command line arguments passed to the program. If you want to use your own string array, you have to declare it.
 
Hope this helps
Nish
 


Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Buy it, read it and admire me Smile | :)

QuestionWhat is the advantage of this code?membera reader2 Dec '01 - 10:34 
I can't help asking the folowing questions:
 
1. Is this code supposed to explain something good about .NET or C#? It seems you can do the thing demonstrated here easily with other technology (MFC for example).
 
2. Does the same code work without heavy modification for other non-microsoft databases, such as Oracle, Sybase, etc. ?
AnswerRe: What is the advantage of this code?memberNish [BusterBoy]2 Dec '01 - 19:11 
a reader wrote:
Is this code supposed to explain something good about .NET or C#? It seems you can do the thing demonstrated here easily with other technology (MFC for example).
 
It's just an introduction for people who want to do OLE DB programming with .NET. It's not something special about .NET.
 
a reader wrote:
Does the same code work without heavy modification for other non-microsoft databases, such as Oracle, Sybase, etc. ?
 
Yes. But you'll need to change the connection string accordingly
 
Nish
 
Sonork ID 100.9786 voidmain
www.busterboy.org
If you don't find me on CP, I'll be at Bob's HungOut
GeneralUpdated for beta 2.0memberNish [BusterBoy]1 Dec '01 - 22:37 
I have updated the article for beta 2.0
When I wrote the article I was on beta 1
 
Nish
 
Sonork ID 100.9786 voidmain
www.busterboy.org
If you don't find me on CP, I'll be at Bob's HungOut
GeneralADO namespacememberAnonymous81819 Nov '01 - 18:42 
I try to compile the sample code and got this.
Is ADO still a valide namespace in .Net SDK Beta 2?
 
thanks
 
The type or namespace name 'ADO' does not exist in the class or namespace 'System.Data' (are you missing an assembly reference?)
GeneralRe: ADO namespacememberNish [BusterBoy]1 Dec '01 - 22:38 
Hi
 
I have updated the article for beta 2.0
I should have done that already, but I kept postponing it.
sorry for the lethargy
 
Nish
 
Sonork ID 100.9786 voidmain
www.busterboy.org
If you don't find me on CP, I'll be at Bob's HungOut
GeneralObsoletememberMN15 Oct '01 - 5:47 
Good morning,
You are problably wakeup, now we are using version Beta 2. Your samples will not work in the current version. There are significant changes!
 
Please, update your development environment, evaluate .Net and bring something more than we can read from the MSDN docs.
 
Thanks.
 
P.S.
Your program missing an exception handling included cleanup connection.
GeneralRe: ObsoletememberNish [BusterBoy]1 Dec '01 - 22:39 
The article has been updated.
I wish you'd log in.
If you had done that, then I'd have got a notification
 
Nish
 
Sonork ID 100.9786 voidmain
www.busterboy.org
If you don't find me on CP, I'll be at Bob's HungOut
Generalgood jobmemberJingo11 Oct '01 - 1:24 
buster
 
Good work again.You could write something like this showing how to select records from a database. Maybe a part-2.
 
Thanks
JingoRose | [Rose]
GeneralRe: good jobmemberNish [BusterBoy]11 Oct '01 - 2:57 
Thank you.
 
yeah, that's an idea...
 
Smile | :)
 
Nish

GeneralYaar, you are the bestmemberAmita Buch13 Oct '01 - 12:32 
This is Gr8 Wink | ;) Wink | ;) Wink | ;) Wink | ;)
GeneralException handlingmemberJason Douglas11 Oct '01 - 1:10 
Perhaps instead of providing a warning that the program will crash with an exception maybe you could add a simple exception handler to the application. Just a thought. Smile | :)
GeneralRe: Exception handlingmemberNish [BusterBoy]11 Oct '01 - 3:00 
Frown | :-(
 
sorry
my mistake...
 
I guess I should have done that...
actually I kinda thought of it then thought exception handling would require further explanations...
 
anyway for those of you who wanta try it out
put the code you wanta try in a try block and catch it in a catch block as shown below:-
 
try
{
//code goes here
}
catch(System.Exception e1)
{
//do your handling here
}
 
regards and thanks
Nish

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 2 Dec 2001
Article Copyright 2001 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid