| 网站首页 | 业界新闻 | 技术文章 | 视频教程 | 下载频道 | 程序源码 | 个人空间 | 编程论坛 |
 
| 技术教程首页 | 开发语言 | WEB开发 | .NET技术 | 数据库 | 操作系统 | 网页制作 |
 
 
您现在的位置: 编程中国 >> 技术教程 >> .NET技术 >> VC.NET >> VC.NET技术资料 >> 正文
  ►  在managed C++应用中使用ADO.NET
在managed C++应用中使用ADO.NET
作者:Tacone译    阅读人次:……    文章来源:51dotnet    发布时间:2006-7-6    网友评论()条
 
  摘要:

  文中就用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;
}

 

 
文章录入:静夜思    责任编辑:静夜思 
  • 上一篇文章: 没有了

  • 下一篇文章:

  •  
    相关文章
    原创地带
    24小时热门帖子