如何将SQL连接到VC ++ [英] How to connect SQL To VC++

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

问题描述



如何编写连接到SQL并获取数据并显示它的代码.

我想在usng C/C ++中做到这一点.

我已经做了很多谷歌搜索,什么都没做.

任何人都有解决方案.请让我知道.

谢谢
:)



How do i write a code that connects to SQL and takes the data and display it.

I want to do this in usng C/C++.

I have done lots of googling on it, didnt got any thing.

Any one have any solution. Pls let me know.

Thanks
:)

推荐答案

以下程序从数据库TestDB中名为TestTable 的表中获取所有数据,并显示给用户
在这里,您需要替换数据源(您的服务器名称),初始目录(您的数据库名称)和表名称
The following program takes all data from a table called TestTable in the database TestDB and displays to the user
Here you need to replace the Data Source(Your server name), Initial Catalog(your DB name) and table name
#include "stdafx.h"
#include <stdio.h>
#include <ole2.h>
#include <iostream>

#import "C:/Program Files/Common Files/System/ado/msado15.dll"  rename( "EOF", "AdoNSEOF" )

using namespace std; 
using namespace ADODB;

_bstr_t bstrConnect("Provider='SQLOLEDB'; Data Source='PC001\\SQLEXPRESS'; Initial Catalog='TestDB'; Integrated Security='SSPI';");
int main() 
{

	HRESULT hResult = CoInitialize( 0 );
    if( FAILED( hResult ))
    {
        return hResult;
    }
    try
    {
        ADODB::_ConnectionPtr pConnect("ADODB.Connection");
        hResult = pConnect->Open( bstrConnect, "admin", "", ADODB::adConnectUnspecified );
        if (SUCCEEDED(hResult))
        {
            _bstr_t query = "SELECT * FROM TestTable;";
            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 hResult;
}


请参考以下线程:
从C ++访问SQL Server [ http://www.sqlapi.com/ [ ^ ]
http://www.codeguru.com/ [ ^ ]
C ++ SQL接口 [
Please refer following thread:
Accessing SQL Server from C++[^]
http://www.sqlapi.com/[^]
http://www.codeguru.com/[^]
C++ SQL Interface[^]


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

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