头文件
database.h文章来源:https://www.toymoban.com/news/detail-574906.html
#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 <tchar.h>
#include<iostream>
#include <string>
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文件文章来源地址https://www.toymoban.com/news/detail-574906.html
#include <iostream>
#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;
}
到了这里,关于ado库——连接sql server数据库的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!