在头文件中要包含
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename ("EOF","serEOF") //serEOF是自己随便起个名字,命名空间
//插入函数① 与②不同是声明了_variant_t RecordsAffected;在生成字符串的时候用左右。
//以SQL语句的方式 插入数据库。
//strsql.Format("insert into student (id,school,name,birth) values ('%d','%s','%s','%s')",
// stu_id,stu_ch,stu_name,stu_birth)
void CadoDlg::OnBnClickedButton3()
{
// TODO: 在此添加控件通知处理程序代码
CoInitialize(NULL);
_variant_t RecordsAffected;
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
pConn->ConnectionString="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=gprs_project"; //gprs_project是自己建的数据库
pConn->Open("","sa","aic",adConnectUnspecified); //sa用户名 aic密码
CString strsql;
strsql="insert into student (id,school,name,birth) values ('1','纳格兰','笑秋水','2008-02-28')";
try{
pConn->Execute((_bstr_t)strsql,&RecordsAffected,adCmdText);
}catch(_com_error e)
{
//抛出异常的作用,1:隐藏错误信息,2:避免程序中断,抛出异常可继续运行。
AfxMessageBox((CString)"增加用户出错=_=~!"+" "+e.ErrorMessage());
}
pRst.Release();
CoUninitialize();
}
//---------------------------------------------------------------//
//写入函数②,调用PutCollect函数进行修改。感到奇怪的是
//如果没有pRst->Open("select * from student",_variant_……)这句代码,插入无法完成。
void CadoDlg::OnBnClickedButton3()
{
stu_id=3;
stu_name="冯会玲";
// TODO: 在此添加控件通知处理程序代码
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
pConn->ConnectionString="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=gprs_project";
//pConn->ConnectionString="Provider=SQLOLEDB.1;Password=aic;Persist Security Info=True;User ID=sa;Initial Catalog=pubs";
pConn->Open("","sa","aic",adConnectUnspecified);
pRst->Open("select * from student",_variant_t((IDispatch*)pConn),
adOpenDynamic,adLockOptimistic,adCmdText);
stu_id=1;
stu_ch="纳格兰";
stu_name="秋水无痕";
stu_birth="2007-01-23";
try{
pRst->AddNew();
pRst->PutCollect("id",(_variant_t)stu_id);
pRst->PutCollect("school",(_variant_t)stu_ch);
pRst->PutCollect("name",(_variant_t)stu_name);
pRst->PutCollect("birth",(_variant_t)stu_birth);
pRst->Update();
pRst->Close();
}catch(_com_error e)
{
//抛出异常的作用,1:隐藏错误信息,2:避免程序中断,抛出异常可继续运行。
AfxMessageBox((CString)"增加用户出错=_=~!"+" "+e.ErrorMessage());
//return false;
}
pRst.Release();
CoUninitialize();
}