如何在VC ++ 2010中通过ODBC连接访问 [英] How to connect to access by ODBC in VC++ 2010

查看:48
本文介绍了如何在VC ++ 2010中通过ODBC连接访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用odbcad32.exe创建了用户DSN.似乎仅与
有关 office 2007 32位可用驱动程序.但是当使用DataSource(同时添加CRecordSet)类时,我提到此DSN,VC ++ 2010专业版(原始)
崩溃而没有任何警告,请在这个问题上帮助我吗?
是否还有其他用于VC ++的数据库连接的简单方法?(我发现ADO对于VC ++有点困难)

I have created user DSN using odbcad32.exe. As it seems only connection with
office 2007 32 bit available drivers.But when for DataSource( while adding CRecordSet) class ,I mention this DSN,VC++ 2010 professional edition(original)
crashes without any warning,Please help me on this issue?
Is there any another simple way of database connection for VC++?(I found ADO is bit difficult for VC++)

推荐答案

使用ADO可以很容易地进行连接.参见下面的代码.它显示访问数据库MyDB
中名为Annount的表中的所有字段.
It is easy connecting using ADO. see the below code. It displays all the fields in a table called Annount from the access database MyDB

#include <iostream>
#include <tchar.h>
#import <C:\\Program Files\\Common Files\\System\\ado\\msado15.dll>  \
    rename( "EOF", "AdoNSEOF" )
using namespace std;

// Connection string for ADO 
_bstr_t bstrConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\MyTrainingDB\\MyDB.accdb;";

int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hResult = CoInitialize( 0 );
    if( FAILED( hResult ))
    {
        return 0;
    }
    try
    {
        ADODB::_ConnectionPtr pConnect("ADODB.Connection");
        hResult = pConnect->Open( bstrConnect, "admin", "", ADODB::adConnectUnspecified );
        if (SUCCEEDED(hResult))
        {
            _bstr_t query = "SELECT * FROM Account;";
            ADODB::_RecordsetPtr pRecSet( "ADODB.Recordset" );
            hResult = pRecSet->Open( query, _variant_t((IDispatch *) pConnect, true), ADODB::adOpenUnspecified,
                                     ADODB::adLockUnspecified, ADODB::adCmdText);
            if( SUCCEEDED( hResult ))
            {
                ADODB::Fields* pFields = NULL;
                hResult = pRecSet->get_Fields( &pFields );
                
                while( !pRecSet->AdoNSEOF )
                {
                    for( long lIndex=0; lIndex < pFields->GetCount(); lIndex++ )
                    {
                        cout<<" | ";
						cout << _bstr_t(pFields->GetItem(lIndex)->GetValue());
                    }
					cout<< "\n----------------------------------------------------------------------------\n";
                    pRecSet->MoveNext();
                }
            }
            pRecSet->Close();
            pConnect->Close();
        }
    }
    catch( _com_error& e )
    {
        // Handle Exception
    }

    // Release COM
    CoUninitialize();
	getchar();
    return 0;
}</tchar.h></iostream>


这篇关于如何在VC ++ 2010中通过ODBC连接访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆