Introduction
This article demonstrates the basics of accessing a database and retrieving data from
that database usingthe ADO.NET data classes.
It uses the .NET ADODataReader
class to retrieve a read-only, forward-only
stream of data from the database. Using the Data Reader can increase
application performance and reduce system overhead becauseonly one row at a time is ever in memory.
This example is based on the standard Managed C++ Application created by the
Application Wizard.
To get an access to the .NET Framework classes we need for
database support, we should add the following lines to the main
source file:
#using <mscorlib.dll>
#using <System.dll>
#using <System.Data.dll>
using namespace System;
using namespace System::Data::ADO;
To retrieve the data from the database we must first create
a connection to the database using the ADOConnection
class.
We then set the ConnectionString
property to specify the data source and then
connect to the database using the Open()
method of the ADOConnection
class.
After that we create a command object to get the data using the
ADOCommand
class. Executing this command returns us a reference to
the data reader class, which is an instance of the ADODataReader
class.
We then loop through each row of data one at the time by calling the Read()
member of the ADODataReader
class. It retrieves data that is accessible
as an items collection. We can get items by index or by column name.
Note: We should always call the Read method before we access the data
in the ADODataReader
object.
int main(void)
{
OleDbConnection* connection;
OleDbCommand* command;
OleDbDataReader* dataReader;
try
{
connection = new OleDbConnection();
connection->set_ConnectionString("Provider=Microsoft.Jet.OLEDB.4.0;"
"Data Source=..\\Data\\grocertogo.mdb;"
"Persist Security Info=False");
connection->Open();
command = new OleDbCommand(S"SELECT ProductName, UnitPrice FROM Products",
connection);
dataReader = command->ExecuteReader();
Console::WriteLine(S"_____________________________________");
Console::WriteLine(S"Product | Price");
Console::WriteLine(S"_____________________________________");
while(dataReader->Read())
Console::WriteLine(S"{0, -30}| {1}", dataReader->get_Item("ProductName"),
dataReader->get_Item("UnitPrice"));
Console::WriteLine(S"_____________________________________");
dataReader->Close();
connection->Close();
}
catch(Exception* e)
{
Console::WriteLine("Error occured: {0}", e->Message);
if (dataReader && !dataReader->IsClosed)
dataReader->Close();
if (connection->State == ConnectionState::Open)
connection->Close();
}
Console::WriteLine("\n\n -- PROGRAM ENDS --\nPress Enter to continue");
Console::ReadLine();
return 0;
}