/* odbc-test-02.cpp: The same very simple ODBC program, but in C++
 * This program compiled and run, without changes, on:
 *   Red Hat Linux 8.0, gcc 3.2, unixODBC 2.2.2
 *     ("g++ -Wall odbc-test-02.cpp -o odbc-test-02 -lodbc")
 *   Windows 2000 Professional, Microsoft Visual C++ 6.0
 *   Windows 2000 Professional, Borland C++ Builder 5.0
 * All of those with Mimer 9.1.3, and Mimer ODBC driver 9.something
 * Thomas Padron-McCarthy (Thomas.Padron-McCarthy@tech.oru.se)
 * October 7, 2003
 */

#include <iostream>
#if defined(_MSDOS) || defined(_WIN32)
#include <windows.h>
#endif
#include "sqlext.h"

using namespace std;

int main() {
  SQLHENV eh;
  SQLHDBC ch;
  SQLHSTMT sh;

  /* ODBC 2.x uses SQLAllocEnv, SQLAllocConnect and SQLAllocStmt.
   * ODBC 3.x uses SQLAllocHandle, with different arguments, for all of those.
   * First: Allocate environment handle.
   */
  if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &eh) != SQL_SUCCESS) {
    cerr << "Kunde inte allokera en ODBC-omgivning.\n";
    return EXIT_FAILURE;
  }

  /* Set the ODBC version attribute,
   * so ODBC knows which ODBC version this application was written for.
   */
  if (SQLSetEnvAttr(eh,
		    SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3,
		    SQL_IS_INTEGER) != SQL_SUCCESS) {
    cerr << "Kunde inte sätta ODBC-versionen till SQL_OV_ODBC3.\n";
    return EXIT_FAILURE;
  }

  /* Allocate connection handle */
  if (SQLAllocHandle(SQL_HANDLE_DBC, eh, &ch) != SQL_SUCCESS) {
    cerr << "Kunde inte allokera ett anslutningsobjekt.\n";
    return EXIT_FAILURE;
  }

  /* Connect: data source, user name, password */
  if (SQLConnect(ch, (SQLCHAR*)"demobasen", SQL_NTS,
		 (SQLCHAR*)"demouser", SQL_NTS,
		 (SQLCHAR*)"fnord", SQL_NTS) != SQL_SUCCESS) {
    cerr << "Kunde inte ansluta till datakällan 'demobasen'.\n";
    return EXIT_FAILURE;
  }

  /* Allocate statement handle */
  if (SQLAllocHandle(SQL_HANDLE_STMT, ch, &sh) != SQL_SUCCESS) {
    cerr << "Kunde inte allokera ett statement handle.\n";
    return EXIT_FAILURE;
  }

  if (SQLExecDirect(sh, (SQLCHAR*)"select Nummer, Namn from Person", SQL_NTS)
      != SQL_SUCCESS) {
    cerr << "Kunde inte köra frågan.\n";
    return EXIT_FAILURE;
  }

  cout << "Personer:\n";
  while (SQLFetch(sh) == SQL_SUCCESS) {
    SQLINTEGER number;
    SQLCHAR name[20 + 1];
    SQLINTEGER number_size, name_size;

    SQLGetData(sh, 1, SQL_C_SLONG, &number, sizeof number, &number_size);
    SQLGetData(sh, 2, SQL_C_CHAR, name, sizeof name, &name_size);

    cout << "Nummer " << number << ", med namnet " << name << "\n";
  }

  SQLFreeHandle(SQL_HANDLE_STMT, sh);
  SQLDisconnect(ch);
  SQLFreeHandle(SQL_HANDLE_DBC, ch);
  SQLFreeHandle(SQL_HANDLE_ENV, eh);

  return EXIT_SUCCESS;
} /* main */

