|
Newbie
Join Date: Mar 2005
Posts: 3
Rep Power: 0 
|
By the way this only has to be a console-based program, so it doesn't need any GUI windows or anything fancy, the simplest sample code would be sufficient. Thanks a lot!
In fact, let me post you the sample code I've got for connecting to a local database using ODBC.
#include <Windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <stdio.h>
//
// function prototypes
//
int main();
//
// main
//
int main()
{
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
SQLRETURN sqlrc;
char sql[1025];
char svalue[2049];
SQLINTEGER inum;
SQLSMALLINT cols;
int i;
char uid[24];
char pwd[24];
char dsn[24];
// connection strings
strcpy(uid, "uid");
strcpy(pwd, "pwd");
strcpy(dsn, "dsn");
// SQL strings
strcpy(sql, "select * from kemp");
// environment handle
sqlrc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
if (sqlrc != SQL_SUCCESS && sqlrc != SQL_SUCCESS_WITH_INFO) {
printf("SQLAllocHandle SQL_HANDLE_ENV Error\n");
return 9;
}
// environment variables settings
sqlrc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
if (sqlrc != SQL_SUCCESS && sqlrc != SQL_SUCCESS_WITH_INFO) {
printf("SQLSetEnvAttr Error\n");
return 9;
}
// connection handle
sqlrc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
if (sqlrc != SQL_SUCCESS && sqlrc != SQL_SUCCESS_WITH_INFO) {
printf("SQLAllocHandle SQL_HANDLE_DBC Error\n");
return 9;
}
// connect
sqlrc = SQLConnect(hdbc, (SQLCHAR*)dsn, SQL_NTS, (SQLCHAR*)uid, SQL_NTS, (SQLCHAR*)pwd, SQL_NTS);
if (sqlrc != SQL_SUCCESS && sqlrc != SQL_SUCCESS_WITH_INFO) {
printf("SQLConnect Error\n");
return 9;
}
// statement handle
sqlrc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
if (sqlrc != SQL_SUCCESS && sqlrc != SQL_SUCCESS_WITH_INFO) {
printf("SQLAllocHandle SQL_HANDLE_STMT Error\n");
return 9;
}
// statement prepare
sqlrc = SQLPrepare(hstmt, (SQLCHAR*)sql, SQL_NTS);
if (sqlrc != SQL_SUCCESS && sqlrc != SQL_SUCCESS_WITH_INFO) {
printf("SQLPrepare Error\n");
return 9;
}
// get result columns
sqlrc = SQLNumResultCols(hstmt, &cols);
if (sqlrc != SQL_SUCCESS && sqlrc != SQL_SUCCESS_WITH_INFO) {
printf("SQLNumResultCols Error\n");
return 9;
}
// execute
sqlrc = SQLExecDirect(hstmt, (SQLCHAR*)sql, SQL_NTS);
// display result in CSV format
while (TRUE) {
sqlrc = SQLFetch(hstmt);
if (sqlrc == SQL_SUCCESS || sqlrc == SQL_SUCCESS_WITH_INFO) {
for (i = 1; i < cols+1; i++) {
if (i > 1) {printf(",");}
strcpy(svalue, "");
SQLGetData(hstmt, i, SQL_C_CHAR, (SQLCHAR*)svalue, 2048, &inum);
printf(svalue);
}
printf("\n");
} else {
if (sqlrc == SQL_NO_DATA) {
printf("\n");
} else {
// otherwise error
printf("SQLFetch ERROR\n");
}
break;
}
}
}
|