您的位置:首页 > 数据库

使用 ado连接数据库

2011-05-24 10:35 197 查看
#include "stdafx.h"
#include <stdio.h>
//禁止4146警告
#pragma warning(disable:4146)
//导入ADO库
#import "C:/Program Files/Common Files/System/ado/msado15.dll" /
no_namespace rename("EOF","rsEOF")    //EOF表示文件尾部,所以将ado中的eof重命名为rseof,并且不使用名字空间

int main()
{
//初始化COM库
::CoInitialize(NULL);
//创建连接对象
_ConnectionPtr pConn(__uuidof(Connection));
//设置连接字符串
pConn->ConnectionString = "Provider=SQLOLEDB.1;"
"Password=123;"
"User ID=sa;"
"Initial Catalog=student;"
"Data Source=111.187.180.5";
//(1)打开到数据库服务器的连接
pConn->Open("","","",adConnectUnspecified);  //第一个参数ConnectionString,如果之前设置了连接字符串,
//这里可以为空,第二个参数和第三个参数是用户名和密码,之前设置
//了可以为空,第四个参数使用adConnectUnspecified表示不指定选项

//创建记录集对象
_RecordsetPtr pRst(__uuidof(Recordset));
//(2)执行SQL语句
pRst = pConn->Execute("Select * From student",NULL,adCmdText);//adCmdText表示普通sql语句,
//adcmdstroedproc表示存储过程
//遍历Select语句查询结果
while(!pRst->rsEOF)
{
//读取结果
printf("%s %s/n",
(char*)((_bstr_t)pRst->GetCollect("sno")),
(char*)((_bstr_t)pRst->GetCollect("sname")));
//读取下一条记录
pRst->MoveNext();
}
//(3)关闭对象
pRst->Close();
pConn->Close();
//释放对象
pRst.Release();
pConn.Release();
pRst = NULL;
pConn = NULL;
//释放COM库
::CoUninitialize();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息