代码改变世界

c++连接mssql

2012-09-17 14:22  hongjiumu  阅读(2017)  评论(16编辑  收藏  举报
# include <iostream>
//# include "stdafx.h"
# include <iomanip>
# import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF", "EndOfFile")
int main()
{
    ::CoInitialize(NULL);

    try
    {
        _ConnectionPtr pConn("ADODB.Connection");
        _RecordsetPtr m_pRecordset("ADODB.Recordset");
        //连接字符串,此处为MSSQL的连接字符串,其他数据库的摆渡一下就知道
        _bstr_t strConnect="Provider=sqloledb;Network Library=DBMSSOCN;Initial Catalog=WDBuyDB;User ID=admin;Password=admin$192;Data Source=192.168.2.199,1433";
        //步骤1--打开连接
        pConn->Open(strConnect,"","",adModeUnknown);
        //步骤2--创建命令
        //步骤3--执行命令
        m_pRecordset=pConn->Execute("SELECT * FROM [WDBuyDB].[dbo].[Pro_ProductAttribute]",NULL,adCmdText);
        //步骤4--操作数据
        //操作数据可以选择其它的删除,修改,插入等这里只是读出数据库中表的数据
        _variant_t ProductAttributeKey,AttributeName,AttributeValue;
        std::cout<<"ProductAttributeKey                      AttributeName             AttributeValue";
        //std::cout<<"n---------------------n";
        while(!m_pRecordset->EndOfFile)
        {
            ProductAttributeKey=m_pRecordset->GetCollect(_variant_t((long)0));
            AttributeName=m_pRecordset->GetCollect(_variant_t((long)1));
            AttributeValue=m_pRecordset->GetCollect(_variant_t((long)2));
            //给字段编号或者是字段名
            //id=m_pRecordset->GetCollect("ProductAttributeKey");
            //name=m_pRecordset->GetCollect("AttributeName");

            if(ProductAttributeKey.vt!=VT_NULL&&AttributeName.vt!=VT_NULL)
            {
                printf("\n");
                //std::cout.setf(ios::left);
                std::cout<<std::setw(18)<<(char*)(_bstr_t)ProductAttributeKey;
                std::cout<<std::setw(10)<<(char*)(_bstr_t)AttributeName;
                std::cout<<std::setw(20)<<(char*)(_bstr_t)AttributeValue;
            }

            //移动到下一条记录
            m_pRecordset->MoveNext();

            //关闭记录集
            m_pRecordset->Close();
        }
    }
    catch(_com_error e)
    {
        //显示错误信息
        //std::cerr << "This is a test message\n";
        std::cerr << (char*)e.Description();
        //std::cerr<<"nERROR:"<<(char*)e.Description();
    }
    getchar();
    ::CoUninitialize();
    return 0;

    //测试部分
    /*
    std::cout << "Hello, world!" << std::endl;
    getchar();
    return 0;
    */
}