使用msado的方式连接MS SQL Server

说明:此种方法不是很建议,建议多使用ODBC的数据源方式,然后使用CDatabase对象连接操作数据库。
数据库的驱动可以多种多样。
1.新建一个命令行的Win32程序即可
包含头文件

#include <afx.h>

2.写入代码

// TestSqlServe.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#import "msado15_xp.dll" no_namespace rename("EOF","adoEOF")

_ConnectionPtr refCon;
//可以连接sqlserver2008 R2
//可以连接sqlserver2003
BOOL ConnectDB()
{
	refCon.CreateInstance(__uuidof(Connection));
	if (refCon == NULL){printf("创建数据库连接失败.\n");	return false;}
	CString strLink;
	strLink.Format("Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s",
		"bwjf~123456",
		"sa",
		"Test",
		"192.168.0.53");

	try {
		refCon->Open((LPCTSTR)strLink, "", "", adModeUnknown);
		printf("链接数据库成功\n");
	}
	catch(_com_error e) {
		printf("链接数据库失败:%s\n",e.ErrorMessage());
		return false;
	}
}

void DbQuery()
{
	try{
		_variant_t vtret;
		_RecordsetPtr lpRecord(__uuidof(Recordset));

		lpRecord=refCon->Execute("select * from con;",0,adCmdText);

		vtret=lpRecord->GetCollect("data");

		while(vtret.vt!=VT_NULL &&  !lpRecord->adoEOF)
		{
			CString temp = CString((LPCTSTR)(_bstr_t)vtret);
			printf("查询数据结果%s\n",temp);
			lpRecord->MoveNext();
		}	
	}catch(_com_error e)
	{
		printf("出错了:%d\n",e.Description());

	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	::CoInitialize(0);
	ConnectDB();
	DbQuery();
	CoUninitialize();
	system("pause");
	return 0;
}

通用的msado的库下载:

猜你喜欢

转载自blog.csdn.net/magaiou/article/details/80322168