建立一个类用来连接数据库
class CDataManage
{
public:
CDataManage();
virtual ~CDataManage();
public:
_RecordsetPtr Record1;
protected:
_ConnectionPtr DataConn;
_RecordsetPtr DataRecord;
public:
_ConnectionPtr GetConn();//获取adoConnection对象
_RecordsetPtr GetRecordset();//获取adoRecordset对象
bool ConnectDatabase(CString constr); //连接数据库
bool ExecSQL(CString sql);
};
CDataManage::CDataManage()
{
DataConn.CreateInstance(_uuidof(Connection)); //????
DataRecord.CreateInstance(_uuidof(Recordset));
Record1.CreateInstance(_uuidof(Recordset));
}
CDataManage::~CDataManage()
{
DataConn->Release();
DataRecord->Release();
Record1->Release();
}
_ConnectionPtr CDataManage::GetConn() //返回数据成员的值
{
return DataConn;
}
_RecordsetPtr CDataManage::GetRecordset() //返回数据成员的值
{
return (DataRecord);
}
bool CDataManage::ConnectDatabase(CString constr) //连接数据库
{
DataConn->ConnectionString = (_bstr_t)constr; //_ConnectionPtr对象
try
{
DataConn->Open("","","",-1);
}
catch(...)
{
return false;
}
return true;
}
bool CDataManage::ExecSQL(CString sql)
{
_bstr_t sqltext =sql;
try
{
DataConn->Execute(sqltext,NULL,adCmdText); //??
}
catch(_com_error& e)
{
AfxMessageBox(e.ErrorMessage(),0,0);
return false;
}
return true;
}
在另一个文件中应用这个类连接数据库
bool change;
datamanage = new CDataManage(); //定义一个用来连接数据库的类对象
change= datamanage->ConnectDatabase("Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=EquipmentManage;Data Source=.");
if (change==false)
{
AfxMessageBox("连接数据库初始化失败");
return 0;
}
求解!!为什么连接不上 哪里出错了
------解决方案--------------------
- SQL code
---连不上,你得把错误提示给出来,才知道是那里的问题啊?---DataConn->Open("","","",-1);????你确定open勒?
------解决方案--------------------