Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sql.h>
#include <sqlext.h>
#pragma lib <ODBC32.lib>
#define SZLEN 50
void process(void);
void dbError( LPSTR lp, HENV henv,HDBC hdbc,HSTMT hstmt);
int main(int argc,char *argv[])
{
process();
return 0;
}
void process(void)
{
long int liid = 0;
char szartist[SZLEN+1];
HSTMT hstmt = SQL_NULL_HSTMT;
SQLRETURN retcode;
HENV henv = SQL_NULL_HANDLE;
HDBC hdbc = SQL_NULL_HANDLE;
char szSql[256];
char szout[256];
char szdatabase[] = "DSN=MS Access Database;DBQ=db1.mdb;FIL=MS Access;";
retcode = SQLAllocEnv(&henv); /* Environment handle*/
if (retcode != SQL_SUCCESS)
{
dbError( "SQLAllocEnv()",henv,hdbc,hstmt);
return;
}
retcode = SQLAllocConnect(henv, &hdbc); /* Connection handle */
if (retcode != SQL_SUCCESS)
{
dbError( "SQLAllocConnect()",henv,hdbc,hstmt);
SQLFreeEnv(henv);
return;
}
retcode = SQLDriverConnect(hdbc, NULL, (SQLCHAR *)szdatabase, (short) (strlen(szdatabase)+1), NULL, 0, NULL, SQL_DRIVER_NOPROMPT); /* Connect to data source */
/* If there was a DSN already set-up instead of SQLDriverConnect you could use
retcode = SQLConnect(hdbc, "my_dsn", SQL_NTS, NULL, 0, NULL, 0);
*/
if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
{
dbError( "SQLDriverConnect()",henv,hdbc,hstmt);
SQLFreeEnv(henv);
return;
}
retcode = SQLAllocStmt(hdbc, &hstmt); /* Statement handle */
if (retcode != SQL_SUCCESS)
{
dbError( "SQLAllocStmt()",henv,hdbc,hstmt);
SQLFreeEnv(henv);
return;
}
lstrcpy( szSql,"SELECT artistID, artistName FROM Artists ORDER BY artistName"); /* Select statement */
retcode = SQLExecDirect(hstmt, szSql, SQL_NTS);
if (retcode != SQL_SUCCESS)
{
dbError( " SQLExecDirect()",henv,hdbc,hstmt);
}
if (retcode == SQL_SUCCESS)
{
while (TRUE)
{
retcode = SQLFetch(hstmt);
if (retcode == SQL_ERROR || retcode == SQL_SUCCESS_WITH_INFO)
{
dbError( "SQLFetch()",henv,hdbc,hstmt);
}
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
retcode = SQLGetData(hstmt, 1, SQL_C_DEFAULT, &liid, 0, NULL);
if (retcode != SQL_SUCCESS)
{
dbError( "SQLGetData(1)",henv,hdbc,hstmt);
SQLFreeEnv(henv);
return;
}
memset(szartist, 0, SZLEN+1);
retcode = SQLGetData(hstmt, 2, SQL_CHAR, szartist, SZLEN, NULL);
if (retcode != SQL_SUCCESS)
{
dbError( "SQLGetData(2)",henv,hdbc,hstmt);
SQLFreeEnv(henv);
return;
}
fprintf(stdout, "ID: %d\tArtist: %s\n", liid, szartist);
}
else
{
break;
}
}
}
SQLFreeStmt(hstmt, SQL_DROP);
SQLDisconnect(hdbc);
SQLFreeConnect(hdbc);
SQLFreeEnv(henv);
}
// ------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------
void dbError( LPSTR lp, HENV henv,HDBC hdbc,HSTMT hstmt)
{
unsigned char buf[250];
unsigned char sqlstate[15];
SQLError( henv, hdbc, hstmt, sqlstate, NULL,buf, sizeof(buf),NULL);
fprintf(stderr, "%s. %s, SQLSTATE=%s\n",lp, buf, sqlstate);
}
Thanks for your help.