Thursday, September 3, 2009

How to use ADO / Database with C++ / VC++

#include
#include
#include
#import "msado15.dll" rename("EOF", "ADOEOF")


void main()
{
HRESULT hr ;
CoInitialize(NULL) ;
try
{
ADODB::_ConnectionPtr connection;
hr = connection.CreateInstance(__uuidof(ADODB::Connection));

if (FAILED(hr))
{
throw _com_error(hr);
}

ADODB::_RecordsetPtr recordset;
hr = recordset.CreateInstance(__uuidof(ADODB::Recordset)) ;
if (FAILED(hr))
{
throw _com_error(hr) ;
}
connection->CursorLocation = ADODB::adUseClient ;

connection->Open(L"Provider=SQLOLEDB.1; Server=myDatabaseServer;Database=myDatabaseName;Uid=myUserId; Pwd=myPassword;", L"",
L"", ADODB::adConnectUnspecified) ;

char s[500] ;
strcpy(s,"INSERT INTO myTableName(FieldName1, FieldName1) VALUES('Value1', value2);") ;

recordset->Open(s,
connection.GetInterfacePtr(), ADODB::adOpenForwardOnly,
ADODB::adLockReadOnly, ADODB::adCmdText) ;

printf("\n Inserted ") ;

recordset->Close() ;

}
catch(_com_error &e)
{
printf("\n << error >> ") ;
}
catch(...)
{
printf("\n %s " , "Unhandled Exception") ;
} ;
}

No comments: