您的位置:首页 > 数据库

VC中使用ADO进行数据库开发的一些资料的整理

2009-04-03 17:10 761 查看
1.导入ado库
在StdAfx.h中,加入如下代码
#import "c:program filescommon filessystemadomsado15.dll"
no_namespace rename("EOF","adoEOF") rename("BOF","adoBOF")

2.Com 初试化
在app的InitInstance中,加入

AfxOleInit();(MFC)
或者
CoInitialize(NULL)

如果用了CoInitialize

退出时,要调用CoUninitialize()

注意,如果在线程中也使用了com,那么在线程中也要用CoInitialize初始

3.连接数据库

_ConnectionPtr m_pAppConn;

hResult = m_pAppConn.CreateInstance(_T("ADODB.Connection"));///创建Connection对象

然后连接之
m_pAppConn->Open("Provider=Microsoft.Jet.OLEDB.4.0 ;
Data Source = .DataBaseaa.mdb",
"","",adModeUnknown);

BOOL OpenConnect()
{
HRESULT hResult;

CloseConnect();

try
{
hResult = m_pAppConn.CreateInstance(_T("ADODB.Connection"));///创建Connection对象
if(SUCCEEDED(hResult))
{
m_pAppConn->Open("Provider=Microsoft.Jet.OLEDB.4.0 ;
Data Source = .DataBaseaa.mdb",
"","",adModeUnknown);
}

}

catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format(_T("连接数据库失败!rn错误信息:%s"),e.ErrorMessage());
AfxMessageBox(errormessage);

hResult = -1L;
}

return (SUCCEEDED(hResult) ? TRUE : FALSE);
}

这里连接的数据库是access数据库,在工程目录下的DataBaseaa.mdb

关键连接的字符窜,
如果是access

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=192.168.1.1DataBaseaa.mdb;
这是局域网上的文件

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.DataBaseaa.mdb;
本机上的

如果是sql 2000
Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Password=sa;Initial Catalog=aa;Data Source=192.168.1.1;
数据库在192.168.1.1上,数据库名字是aa

4.关闭连接

BOOL CloseConnect()
{
HRESULT hResult=0;

try
{
if(m_pAppConn!=NULL)
{
if(m_pAppConn->State!=adStateClosed)
{
hResult=m_pAppConn->Close();
}

m_pAppConn.Release();
}
}

catch(_com_error e)
{
_bstr_t bstrSource(e.Source());

_bstr_t bstrDescription(e.Description());

TRACE(_T("n Source : %s n Description : %s n"),(LPCSTR)bstrSource,(LPCSTR)bstrDescription);

hResult=-1L;

}

return (SUCCEEDED(hResult) ? TRUE : FALSE);

}

5.使用recodeset打开记录

  _variant_t RecordsAffected;
_RecordsetPtr pRecordset = NULL;

strSql = _T("SELECT field FROM table");

pRecordset.CreateInstance(_uuidof(Recordset));
pRecordset = pConn->Execute (_bstr_t(strSql) , &RecordsAffected , adCmdUnknown);

其中&RecordsAffected 可以获得有多少记录返回,这是记录的影像数目

6.关闭记录集
 if(pRecordset != NULL && pRecordset->State)
{
pRecordset->Close();
pRecordset = NULL;
}

7.判断是否为空
 if (pRecordset->adoBOF && pRecordset->adoEOF)
{
//MessageBox("没有符合条件的记录存在!","提示");
if(pRecordset != NULL && pRecordset->State)
{
pRecordset->Close();
pRecordset = NULL;
}
return;
}

8,从记录集取数据
   
_variant_t var;

  pRecordset->MoveFirst();

for(;!pRecordset->adoEOF;pRecordset->MoveNext())
{
var = pRecordset->GetCollect(_T("field"));
}

9.几种常见数据的转换
 如果是字符窜的字段

  var = pRecordset->GetCollect(_T("field"));
if(var.vt!=VT_NULL)
{
str= (LPCTSTR)_bstr_t(var);
}

if(var.vt!=VT_NULL)
判断是必须的,如果是空,转换会出错

如果是int形
int aa = atoi(str)

_variant_t是个可变类型,支持很多种类型,

10.使用command

利用Command对象来执行SQL命令
_CommandPtr m_pCommand;
m_pCommand.CreateInstance("ADODB.Command");
_variant_t vNULL;
vNULL.vt = VT_ERROR;
vNULL.scode = DISP_E_PARAMNOTFOUND;///定义为无参数
m_pCommand->ActiveConnection = m_pConnection;///非常关键的一句,将建立的连接赋值给它
m_pCommand->CommandText = "SELECT * FROM users";///命令字串
m_pRecordset = m_pCommand->Execute(&vNULL,&vNULL,adCmdText);///执行命令,取得记录集

如果使用记录集的open来打开command对象.
如果在 Source 参数中传送 Command 对象并且同时传递 ActiveConnection 参数,那么将产生错误。Command 对象的 ActiveConnection 属性

必须已经设置为有效的 Connection 对象或者连接字符串。

所以
_variant_t vNULL;
vNULL.vt = VT_ERROR;
vNULL.scode = DISP_E_PARAMNOTFOUND;
_CommandPtr pCommand;
...
m_pRecordset->Open(_variant_t( (IDispatch*)pCommand, true),vNULL,CursorType, LockType, lOption )

11.关于数据中时间的处理
首先,sql语句中有很多时间处理的函数,可以拿来使用,如果不使用这些函数,那么直接用sql语句来拼写

CString strDate= "2006-8-11";

CString strsql;

strsql.Format("SELECT * FROM Table where Date=#%s#",strDate);

m_pRecordset->Open(_bstr_t(strsql),
theApp.m_pConnection.GetInterfacePtr(),
adOpenDynamic,
adLockOptimistic,
adCmdText);

accee用#时间,其他大部分都是用''来括的

如果返回得到一个时间,那么
CString类型的变量转化成COleDateTime

COleDateTime::ParseDateTime

或者

CString str = "2004-07-08 11:22:33";
COleVariant VariantTime;
VariantTime = str;
VariantTime.ChangeType(VT_DATE);
COleDateTime DataTime = VariantTime;

反过来转,更简单了,
COleDateTime有format 函数,包括CTime也有这样的函数

12,插入或者删除记录
 strSql.Format(_T(" INSERT INTO table VALUES('%s','%s','%s','%s',#%s#)"),
strID,strName,strAuthor,strPublisher,strDate);

try
{
pConn->Execute (_bstr_t(strSql) , &RecordsAffected , adCmdUnknown);
}

删除也是类似的

添加删除的话,是不返回记录集的,其他的地方,和查询是一样的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: