ODBC Hello World Example (Open Database Connectivity)

See related: Windows API examples

There are four ODBC functions that standout here: SQLConnect(), SQLExecDirect(), SQLFetch() and SQLGetData(). SQLExecDirect() takes an SQL statement as a parameter. SQLFetch() retrieves those data returned by the SQL statement and uses a forward-only (aka non-scrollable) cursor meaning that the application cannot move back to retrieve data that it has already retrieved. SQLGetData() copies the data to variables. Below, find the settings for the ODBC Text Driver DSN named "hello". The ODBC DSN's can be found under Administrative Tools in the control panel of a Windows PC. There are other alternatives to using SQLConnect(), for example, SQLDriverConnect().

#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <tchar.h>

#define MAX_DATA			100

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	RETCODE rc;             // Return code for ODBC functions
	HENV henv;              // Environment handle
	HDBC hdbc;              // Connection handle
	HSTMT hstmt;            // Statement handle
	char szData[MAX_DATA];  // Variable to hold data retrieved
	SDWORD cbData;          // Output length of data

	SQLAllocEnv(&henv);
	SQLAllocConnect(henv, &hdbc);
	SQLConnect(hdbc, _T("hello"), SQL_NTS, NULL, 0, NULL, 0); // "hello" refers to the DSN
	SQLAllocStmt(hdbc, &hstmt);								 // or Data Source Name
	SQLExecDirect(hstmt, _T("SELECT * FROM hello.txt"), SQL_NTS);
	rc = SQLFetch(hstmt);
	while( rc == SQL_SUCCESS ) {
	SQLGetData(hstmt, 1, SQL_C_CHAR, szData, sizeof(szData), &cbData);
	MessageBoxA(NULL, szData, "ODBC", MB_OK);
	rc = SQLFetch(hstmt);
	}
	SQLFreeStmt(hstmt, SQL_DROP);
	SQLDisconnect(hdbc);
	SQLFreeConnect(hdbc);
	SQLFreeEnv(henv);
	return(TRUE);
}
ODBC API Hello World!
ODBC API Hello World DSN Setup 1
ODBC API Hello World DSN Setup 2
ODBC API hello.txt

Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK