【VC开源代码栏目提醒】:网学会员为需要VC开源代码的朋友们搜集整理了ADONET1.cpp相关资料,希望对各位网友有所帮助!
// 这是使用应用程序向导生成的 VC++
// 应用程序项目的主项目文件。
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
#using <System.dll> // 用于Console I/O
#using <System.Data.dll> // 用于ADO.NET
using namespace System;
using namespace System::Data; // 定义ADO.NET结构的一组类
using namespace System::Data::SqlClient; // 定义SQL Server 数据提供的一组类
// 这是此应用程序的入口点
int _tmain(void)
{
// TODO: 请用您自己的代码替换下面的示例代码。
// 创建一个SqlConnection 对象
SqlConnection * cnPubs = new SqlConnection();
// 设置连接字符串
cnPubs->ConnectionString = S"data source=(local);\
integrated security=true;initial catalog=Pubs";
try
{
// 与数据源(本机SQL Server Pubs库)建立连接
cnPubs->Open();
Console::WriteLine(S"与数据源Pubs库的连接成功!");
// 创建一个SqlCommand 对象
SqlCommand * cmTitles = new SqlCommand();
//命令内容是从Titles表格中选择记录数
cmTitles->CommandText = S"SELECT COUNT(*) FROM Titles";
//命令类型是SQL语句
cmTitles->CommandType = CommandType::Text;
//使用连结对象SqlConnection * cnPubs
cmTitles->Connection = cnPubs;
// 执行上述SQL语句,返回一个标量值(Titles表格记录数18)并显示出来
Object * numberOfTitles = cmTitles->ExecuteScalar();
Console::Write(S"Pubs库中Titles表格记录数: ");
Console::WriteLine(numberOfTitles);
// 修改Titles表格中价格price(增加5%),并显示被修改的记录数
cmTitles->CommandText = S"UPDATE titles SET price = price * 1.05 WHERE price IS NOT NULL";
int rowsAffected = cmTitles->ExecuteNonQuery();
Console::Write(S"Titles表格中price已调整的记录数: ");
Console::WriteLine(rowsAffected);
// 对命令对象重新赋值命令文本,查询只取title,price两个字段
cmTitles->CommandText = S"SELECT title, price FROM titles";
// 执行命令对象的ExecuteReader方法 ,返回一个SqlDataReader 类型对象 reader
SqlDataReader * reader = cmTitles->ExecuteReader();
// 执行SqlDataReader的Read方法并将结果显示出来
Console::WriteLine(S"\n-----列出Titles表格中title, price两个字段-----");
while (reader->Read())
{
Console::Write(reader->GetString(0));
Console::Write(S", ");
if (reader->IsDBNull(1))
Console::WriteLine(S"No price yet");
else
Console::WriteLine(reader->GetDecimal(1));
}
Console::WriteLine(S"------------Titles表格记录终止------------------\n");
// Close the reader
reader->Close(); //关闭reader对象
}
//如果上述操作出错,在此作异常处理。显示出错信息
catch (SqlException * Xcp)
{
Console::Write(S"对Pubs库操作出错: \n");
Console::WriteLine(Xcp->Message);
Console::ReadLine();
return 0;
}
// 关闭与数据源的连接
if (cnPubs->State != ConnectionState::Closed)
{
cnPubs->Close();
}
Console::WriteLine(S"现在关闭了与数据源Pubs库的连接");
Console::ReadLine();
return 0;
}
上一篇:
AdoDlg.cpp
下一篇:
谈初中数学“一元二次方程”的几种常见题型