Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to use ODBC for connect to a database and read a table

databases

how to use ODBC for connect to a database and read a table

by  Cagliostro  Posted    (Edited  )
this is a short sample of using ODBC
all rc = something means you must the next verify this rc. I did not put error verification code

#include<iostream>
#include<string>
#include<sql.h>
#include<sqlext.h>
using namespace std;
int main()
{
HENV hEnv;
HDBC hDbc;
RETCODE rc;
int iOut;
char strOut[256];
char szDSN[256] = "driver={Microsoft Access Driver (*.mdb)};dbq=[c:\\db1.mdb];";
//dsn samples:
//"driver={Microsoft Access Driver (*.mdb)};dbq=[f:\\db1.mdb];"
//"driver={SQL Server};pwd={password there};Server={server name};Database={dbname there}"
//driver names for different databases:
//{SQL Server}
//{Microsoft ODBC for Oracle}
//{Oracle in oracle9}
//{Microsoft Access Driver (*.mdb)}
//{MySQL ODBC 3.51 Driver}

char* szSql = "select * from table1";
rc = SQLAllocEnv(&hEnv);
rc = SQLAllocConnect(hEnv, &hDbc);

rc = SQLDriverConnect(hDbc, NULL, (unsigned char*)szDSN,
SQL_NTS, (unsigned char*)strOut,
255, (SQLSMALLINT*)&iOut, SQL_DRIVER_NOPROMPT);
{
int ival;
char chval[128];
int ret1;
int ret2;
HSTMT hStmt;
rc = SQLAllocStmt(hDbc,&hStmt);
rc = SQLPrepare(hStmt,(unsigned char*)szSql, SQL_NTS);//1
//rc = SQLBindCol(hStmt, tab_column, tr_type, tr_value, tr_len, len_or_ind);
rc = SQLBindCol(hStmt, 1, SQL_C_ULONG, &ival, 4, (SQLINTEGER*)& ret1);
rc = SQLBindCol(hStmt, 2, SQL_C_CHAR, chval, 128, (SQLINTEGER*)&ret2);
rc = SQLExecute(hStmt); //2
//if you have queries like drop/create/many update...
//instead of //1 //2 and //3 you could use
//rc=SQLExecDirectA(hStmt,(unsigned char*)szSql,SQL_NTS);
cout<< ">table:"<< endl;
while(1) //3
{
rc = SQLFetch(hStmt);
if(rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)break;
cout<< "{"<< ival<<"}{"<< chval<< "}"<< endl;
}
rc=SQLFreeStmt(hStmt, SQL_DROP);
}
rc = SQLDisconnect(hDbc);
rc = SQLFreeEnv(hEnv);
return 0;
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top