一、初始化
首先,在stdafx.h文件中加入:
#import "C:/Program files/common files/System/ado/msado15.dll " no_namespace rename( "EOF ", "EndOfFile ")
定义变量
_ConnectionPtr ADOConn;
_RecordsetPtr m_pADOSet;
二、连接
//SQL SERVER数据库连接
::CoInitialize(NULL);
//@@@@@@@@@@@@@@@@@@@@@@@@@@
szConn.Format("Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s", strPsd, strUser, strDatabase, strServer);
Password=%s <===> strPsd 密码
User ID=%s <===> strUser 用户
Initial Catalog=%s <===> strDatabase 初始数据库
Data Source=%s <===> strServer SQL服务器
//@@@@@@@@@@@@@@@@@@@@@@@@@@
CString strConnect;
strConnect= "Provider=sqloledb.1;Data Source=192.168.0.131;Initial Catalog=mynet;UID=sa;Integrated Security=SSPI ";
//mynet数据库名字,我使用的是非数据源方式
try
{
ADOConn.CreateInstance(__uuidof(Connection));
ADOConn-> Open((const char *)strConnect, " ", " ",adModeUnknown);//adConnectUnspecified
}
catch(...)
{
AfxMessageBox( "数据库初始化错误,程序将关闭! ");
return FALSE;
}
三、初始化ADO记录集
m_pADOSet.CreateInstance(__uuidof(Recordset));
_variant_t strSQL;
strSQL= "select * from kk ";
if ( m_pADOSet-> State == adStateOpen)
m_pADOSet-> Close();
try
{
m_pADOSet-> CursorLocation=adUseClient;
m_pADOSet-> Open( "select * from kk ", ADOConn.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdUnknown);
}
catch(_com_error &e)
{
CString err;
err.Format( "ADO Error: %s ",(char*)e.Description());
}
int iCount;
iCount = m_pADOSet-> GetRecordCount();
四、查询数据
_variant_t Holder;
int T0;
while(!m_pADOSet-> EndOfFile)
{
Holder = m_pADOSet-> GetCollect( "id ");
//if(Holder.intVal!=VT_NULL)
T0=Holder.intVal;
m_pADOSet-> MoveNext();
}
五、添加数据
m_pADOSet-> AddNew();
m_pADOSet-> PutCollect( "id ",_variant_t( "23 "));
m_pADOSet-> PutCollect( "username ",_variant_t( "salkfj "));
m_pADOSet-> Update();
六、修改数据
m_pADOSet-> EditMode;
m_pADOSet-> PutCollect( "id ",_variant_t( "3 "));
m_pADOSet-> PutCollect( "username ",_variant_t( "saj123456789 "));
m_pADOSet-> Update();
七、删除数据
m_pADOSet-> Delete(adAffectCurrent);//删除当前记录
八、断开数据库
//释放ADO连接对象
if(adStateOpen == ADOConn-> State)
ADOConn-> Close();
ADOConn.Release();
// 释放ADO记录集
if(adStateOpen==m_pADOSet-> State)
m_pADOSet-> Close();
m_pADOSet.Release();
原问题链接:http://topic.csdn.net/u/20070913/17/ccc137bc-020b-472c-94ca-6ca9acf53618.html