一下代码全部测试通过:
连接数据库代码如下:
HRESULT hr;
CoInitialize(NULL);
CString strSQL;
_variant_t user_name;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");
if (SUCCEEDED(hr))
{
//connect database
_bstr_t strConnect="Provider=SQLOLEDB.1;
Initial Catalog=tijian;
Data Source=210.40.16.43";
hr = m_pConnection->Open(strConnect,"sa","111111",adModeUnknown);
//AfxMessageBox("连接成功");
}
}
catch (_com_error e)
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);
return ;
}
【ADO数据库编程】查询数据库代码
CString sql="select * from data";
_variant_tName,Userid;
sql=("SELECT idCard,Name fromUserinfo where Name='"+m_strUser+"' ");
// 自己根据自己的数据库表进行修改
try
{
_variant_t RecordsAffected;
m_pRecordset = m_pConnection->Execute((_bstr_t)sql,NULL, adCmdText);
while(!m_pRecordset->adoEOF)
{
// _variant_tName;
Name=m_pRecordset->GetCollect("name");
Userid=m_pRecordset->GetCollect("idCard");
// name=(_bstr_t)Name;
// //m_Name.Format("%s",(_bstr_t)Name);
//((CComboBox*)GetDlgItem(IDC_COMBO4))->AddString((_bstr_t)Name);
//向组合框3添加(_bstr_t)Name值,,_bstr_t-ADO数据类型转换,重要
m_pRecordset->MoveNext();
}
m_pRecordset->Close();
}
catch (_com_error e)
{
CString errormessage;
errormessage.Format("用户信息未注册!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);
return ;
}
插入数据库代码:
sql=" insert into Userinfo(idcard,name,age,sex,phone,province,city,country,address) values('"+idcard+"','"+name+"','"+age+"','"+sex+"','"+phone+"','"+province+"','"+city+"','"+country+"','"+address+"')";
//常量插入('2','4')这类形式
//sql = ("insert into Userinfo('name','age') values('www','2222')");
try
{
m_pConnection->Execute((_bstr_t)sql,NULL, adCmdText);
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox("用户信息录入错误");
///显示错误信息
flag=0;
}