下面例子依次调用了:
- 初始化环境
- 连接SQL Server
- 执行查询
- 关闭连接
示例代码:
oledbTest.cpp
点击(此处)折叠或打开
- #include "stdafx.h"
- #include <windows.h>
- #include <sys\timeb.h>
- #include <time.h>
- #include <stdio.h>
- #include <iostream>
- #include <map>
- #include <atldbcli.h>
- #include <atlconv.h>
- using namespace std;
-
- typedef struct result
- {
- char ename[19];
- char cname[100];
- DBSTATUS dwEnameStatus;
- DBSTATUS dwCnameStatus;
- } RESULT;
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- HRESULT hr;
- CDataSource m_ds;
- CSession m_session;
-
- //连接串指定数据库,用户名,密码
- char szConnectionString[512] = "Provider=SQLNCLI10.1;Data Source=10.2.0.10;Initial Catalog=MYDB;User ID=user;Password=passwd;Application Name=SQLSERVER;MARS Connection=True";
-
- ::CoInitialize(NULL);
-
- //连接数据库
- hr = m_ds.OpenFromInitializationString(CA2W(szConnectionString));
-
- //打开会话
- hr = m_session.Open(m_ds);
- DBORDINAL ulColumns = 0;
- CDBPropSet dbPropSet(DBPROPSET_ROWSET);
- CCommand<CManualAccessor, CRowset, CNoMultipleResults> m_command;
- hr = m_command.CreateCommand(m_session);
-
- CComPtr<ICommandText> spCommandText;
- hr = m_command.m_spCommand->QueryInterface(&spCommandText);
- USES_CONVERSION;
-
- //查询语句
- const TCHAR *cmd = _T(" select col1, col2 from table1 ");
-
- hr = spCommandText->SetCommandText(DBGUID_SQL, T2COLE(cmd));
-
- dbPropSet.AddProperty(DBPROP_ISequentialStream, true);
-
- hr = m_command.Open(&dbPropSet, NULL, false);
-
- DBCOLUMNINFO *m_pColumnInfo;
- LPOLESTR m_pStrings;
-
- //获取列信息
- hr = m_command.GetColumnInfo(&ulColumns
- , &m_pColumnInfo
- , &m_pStrings);
-
- BYTE * m_pRowInfoBuff;
-
- //初始化列绑定字段
- DBCOUNTITEM cbRowSize = (m_pColumnInfo[0].ulColumnSize + 1) * sizeof(CHAR);
- DBCOUNTITEM cbRowSize2 = (m_pColumnInfo[1].ulColumnSize + 1) * sizeof(CHAR);
-
- RESULT rst;
-
- int bufferSize = sizeof(rst.ename) + sizeof(rst.cname) +1;
- m_pRowInfoBuff = new BYTE[bufferSize];
-
- hr = m_command.CreateAccessor(ulColumns, m_pRowInfoBuff, (DBLENGTH)bufferSize);
-
- //DBORDINAL* pLength = (DBORDINAL*)(m_pRowInfoBuff + cbRowSize);
- //DBSTATUS* pStatus = (DBSTATUS*)(m_pRowInfoBuff + cbRowSize);
- DBTYPE dbType=DBTYPE_STR;
- DBLENGTH dbLength = (m_pColumnInfo[0].ulColumnSize + 1) * sizeof(TCHAR);
- DBLENGTH dbLength2 = (m_pColumnInfo[1].ulColumnSize + 1) * sizeof(TCHAR);
-
- //m_command.AddBindEntry(1, dbType, dbLength, pValue, pLength, pStatus);
- m_command.AddBindEntry(1, dbType, dbLength, rst.ename, NULL, &rst.dwEnameStatus);
- m_command.AddBindEntry(2, dbType, dbLength2, rst.cname, NULL, &rst.dwCnameStatus);
-
- hr = m_command.Bind();
-
- //获取查询信息
- while(S_OK == m_command.MoveNext())
- {
- printf(" ename = [%s] ,cname = [%s]\n", rst.ename, rst.cname);
- }
-
- //关闭连接
- m_command.Close();
- m_session.Close();
- m_ds.Close();
-
- ::CoUninitialize();
-
- ::getchar();
-
- }