odbc
时间:2010-08-10 来源:light511
#include<iostream>
#include<windows.h>
#include<sqltypes.h>
#include<sqlext.h>
#include<sql.h>
using namespace std;
int main()
{
SQLHENV hEnv=SQL_NULL_HENV;
SQLHDBC hDBC=SQL_NULL_HDBC;
SQLHSTMT hSTMT=SQL_NULL_HSTMT;
SQLRETURN rc = SQL_SUCCESS;
SQLCHAR sqlstmt[200];
SQLAllocHandle(SQL_HANDLE_ENV,NULL,&hEnv);
SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION,(SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER);
SQLAllocHandle(SQL_HANDLE_DBC,hEnv,&hDBC);
SQLAllocHandle(SQL_HANDLE_STMT,hDBC,&hSTMT);
SQLWCHAR mydns[50],myuid[50],mypwd[50];
char dns[50], uid[50],pwd[50];
strcpy(dns,"odbctest");
strcpy(uid,"lhf");
strcpy(pwd,"light511");
strcpy((char*)mydns,dns);
strcpy((char*)myuid,uid);
strcpy((char*)mypwd,pwd);
rc=SQLConnect(hDBC, mydns, SQL_NTS, myuid, SQL_NTS,mypwd, SQL_NTS);
if(rc!=SQL_SUCCESS )
{
printf("connect error!\n");
return 0;
}
strcpy((char *)sqlstmt, "SELECT * FROM test1@mydb");
rc=SQLExecDirect(hSTMT,(SQLWCHAR *)sqlstmt,SQL_NTS);
if(rc!=SQL_SUCCESS )
{
printf("execute error!\n");
return 0;
}
SQLCHAR username[50];
SQLINTEGER myid,idlenptr,namelenptr;
rc=SQLBindCol(hSTMT,1,SQL_C_ULONG,(SQLPOINTER)&myid,0,(SQLINTEGER *)&idlenptr);
if(rc!=SQL_SUCCESS )
{
printf("bind error!\n");
return 0;
}
SQLBindCol(hSTMT,2, SQL_C_CHAR,(SQLPOINTER)username,(SQLINTEGER)50,(SQLINTEGER *)&namelenptr);
rc=SQLFetch(hSTMT);
if(rc!=SQL_SUCCESS )
{
printf("fetch error!\n");
return 0;
}
printf("\nmyid=%i,\tusername = %s", myid,username);
SQLDisconnect(hDBC);
SQLFreeHandle(SQL_HANDLE_DBC,hDBC);
SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
return 0;
}