摘要:
文中就用ADO.NET數據對象訪問數據庫及從數據庫回取數據的基本原理作出示例說明。
正文:
本文提供了一個由應用向導生成的基於標准Managed C++應用的實例,它用.NET的ADODataReader類從數據庫中取回一個只讀(read-only)、只前移(forward-only)的數據流。就是因為在內存中一次僅一行,可用數據讀取器(Data Reader)產生應用執行和化簡系統套頭(overhead)。在主源文件增加如下代碼能獲取對具有數據庫支持的.NET Framework類的訪問:
#using
// Add access to .NET Framework classes.
#using
#using
using namespace System;
using namespace System::Data::ADO;
為從數據庫中取回數據,先用ADOConnection類生成一個對數據庫的連接,然後設置ConnectionString屬性指定數據源,用ADOConnection類的Open()方法連到數據庫。
之後用ADOCommand類生成一個command對象以獲取數據,執行命令返回一個數據讀取器(data reader)類的引用,即ADODataReader類的一個實例。
接著循環調用ADODataReader類的Read()成員一次一行地遍歷所有數據行,所取得的數據象一個項目集合(items collection)一樣可訪問,我們可用索引值或列名來獲取各項。注意:在訪問ADODataReader對象中的數據前,應先調用Read方法。
int main(void)
{
ADOConnection* connection; // ADO connection.
ADOCommand* command; // ADO command
ADODataReader* dataReader; // ADO data reader
try
{
// Create connection, set connection string and open connection to
// specified database.
connection = new ADOConnection();
connection->ConnectionString = S"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 ADOCommand(S"SELECT ProductName, UnitPrice FROM Products", connection);
command->Execute(&dataReader);
// 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 == DBObjectState::Open)
connection->Close();
}
Console::WriteLine("Press ENTER to continue");
Console::ReadLine();
return 0;
}