ado库——连接sql server数据库

头文件
database.h

#pragma once

// 说明:#import的这个路径,windows系统里面自带有ado的动态库。
//不同的操作系统可能msado15.dll这个库的名字不一样,这里以windows10为例,我这里是msado15.dll
#import "C:\Program Files\Common Files\System\ado\msado15.dll"  \
rename("EOF", "adoEOF"), rename("BOF", "adoBOF")

// 忽略警告
//#pragma warning(default:4146)

//#include "stdafx.h"
#include 
#include
#include 

using namespace std;
using namespace ADODB;

//定义数据库连接类
class ADOConn
{
public:
	_ConnectionPtr m_pConnection;
	_RecordsetPtr m_pRecordset;
public:
	ADOConn();
	virtual ~ADOConn() {};
	void OnInitADOConn();//初始化连接
	void ExecuteSQL(_bstr_t bstrSQL);//执行SQL语句

};

cpp文件

#include 
#include "database.h"

//构造函数定义
ADOConn::ADOConn()
{
	CoInitialize(NULL); //初始化必不可少
	HRESULT hr = m_pConnection.CreateInstance(_uuidof(Connection));
	if (FAILED(hr))
		cout << "_ConnectionPtr对象指针实例化失败!!!" << endl;
}
//初始化连接函数定义
void ADOConn::OnInitADOConn()
{
	try
	{	//在COM接口中,参数若为字符串, 一定要用BSTR  
		_bstr_t con_bstr = "Driver={sql server};server=192.168.0.151,1433;uid=sa;pwd=3edc9ijn~;datsbase=test";
		if (m_pConnection->State)
			m_pConnection->Close();
		m_pConnection->Open(con_bstr, "","", adModeUnknown);// adModeUnknown 缺省,当前的许可权未设置
	}
	catch (_com_error& e)
	{
		std::cout << "连接异常" << std::endl;
		std::cout << e.Description() << std::endl;
	}
}

//执行SQL语句函数定义
void ADOConn::ExecuteSQL(_bstr_t bstrSQL)
{
	try
	{
		//你的ADO代码
		m_pRecordset = m_pConnection->Execute(bstrSQL, NULL, adCmdText);
	}
	catch (_com_error& e)
	{
		cout << e.Description();
	}
}

int main(int argc, _TCHAR* argv[])
{
	ADOConn con;
	con.OnInitADOConn();
	//float x = 12.3f;
	//float y = 34.5f;
	//float r = 1.1f;
	//char* data = new char[255];
	//sprintf_s(data,sizeof(data) ,"insert into DB_points.dbo.tb_location(X,Y,R) values(%f,%f,%f)", x, y, r);//将SQL语句存放到data
	//string str = data;
	//_bstr_t strSql = str.c_str();//string类型转化为_bstr_t类型
	_bstr_t strSql = "INSERT INTO [test].[dbo].[user](userName,passWord,realName,isActive) values('liu','2345','韩',1)";
	con.ExecuteSQL(strSql);
	//delete[]data;//释放内存
	con.m_pConnection->Close();
	::CoUninitialize();
	system("pause");
	return 0;

}


你可能感兴趣的:(数据库,C++,数据库,ado)