C++ read sqlserver sample share

  • 2020-04-02 02:06:48
  • OfStack


//Readsqlconsole.cpp: main project file.
#include "stdafx.h"
#include <iostream>
#include<iostream>
#include<iomanip>//for setw()
#include"windows.h"
#import "C:Program FilesCommon FilesSystemadomsado15.dll" no_namespace rename("EOF","EndOfFile")
using namespace System;
using namespace std;
int main(array<System::String ^> ^args)
{
    ::CoInitialize(NULL);
    //The type is defined in msado15.dll
    _RecordsetPtr m_pRecordset("ADODB.Recordset");
    _ConnectionPtr m_pConnection("ADODB.Connection");
    _bstr_t bstrSQL("select * from er_order where pactnumber like '13010000%' order by pactnumber"); //The corresponding SQL statement
    try
    {
        clog << " Connecting to database ..." << endl;
        m_pConnection.CreateInstance("ADODB.Connection");//Create a Connection object
        //Set the connection string, which must be of type BSTR or _bstr_t
        _bstr_t strConnect = "Provider=SQLOLEDB; Server= [database example] ;Database= Database name ; uid= Database user ; pwd= 【 password 】 ;";
        m_pConnection->Open(strConnect, "", "", adModeUnknown);//Server connection
        if (m_pConnection == NULL)
        {
            std::cerr << "Lind data ERROR!n";
        }
        m_pRecordset.CreateInstance(__uuidof(Recordset));//Create a recordset object
        //Gets the records in the table
        m_pRecordset->Open(bstrSQL, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
        _variant_t PactNumber, OrigCount;//Fields in the corresponding library
        cout << "-------------- The contract list --------------" << endl;
        while (!m_pRecordset->EndOfFile)
        {
            PactNumber = m_pRecordset->GetCollect("Pactnumber");
            OrigCount = m_pRecordset->GetCollect("Origcount");
            cout << " The contract no. :" << setw(10) << (char*)(_bstr_t)PactNumber;
            cout << "    Sign the bill amount :" << setw(7) << (char*)(_bstr_t)OrigCount << endl;
            m_pRecordset->MoveNext();//Next record
        }
        m_pRecordset->Close();//Close recordset
    }
    catch (_com_error e)//The catching
    {
        cerr << "nERROR:" << (char*)e.Description();
    }
    if (m_pConnection->State)
    {
        m_pConnection->Close();
    }
    ::CoUninitialize();
    Console::ReadLine();

    return 0;
}


Related articles: