|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionThis article demonstrates the basics of accessing a database and retrieving data from that database usingthe ADO.NET data classes. It uses the .NET 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> // Add access to .NET Framework classes. #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 After that we create a command object to get the data using the
We then loop through each row of data one at the time by calling the int main(void) { OleDbConnection* connection; // ADO connection. OleDbCommand* command; // ADO command OleDbDataReader* dataReader; // ADO data reader try { // Create connection, set connection string and open connection to // specified database. connection = new OleDbConnection(); connection->set_ConnectionString("Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=..\\Data\\grocertogo.mdb;" "Persist Security Info=False"); connection->Open(); // Create command and get data reader by executing this command. command = new OleDbCommand(S"SELECT ProductName, UnitPrice FROM Products", connection); dataReader = command->ExecuteReader(); // Print table header Console::WriteLine(S"_____________________________________"); Console::WriteLine(S"Product | Price"); Console::WriteLine(S"_____________________________________"); // Iterate through rows set and print data. while(dataReader->Read()) Console::WriteLine(S"{0, -30}| {1}", dataReader->get_Item("ProductName"), dataReader->get_Item("UnitPrice")); // Print table footer. Console::WriteLine(S"_____________________________________"); // Close DataReader dataReader->Close(); // Close connection. connection->Close(); } catch(Exception* e) { // Print error message and close connection. 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; }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||