Hi! :))))
I have to use sql connection to take queries from user by using textbox structure .How can I provide this .I don't find it anywhere .
especially how can I connect sql and textbox structure together I do not know anything about this subject.

I know c and c++ languages and I want to do a program which uses sql with c++
For example,I have a database and table in sql and there is a button near the table's name
when I click on this button or I enter knowledge as year and etc
,after clicking the button ,some queries in sql format will be come to the screen .How can I do this by using c++ and How can I use the some libraries in c++ by using sql

Hello Nihan1,

Below (if it all fits) is a C console program that uses direct ODBC function calls to create an Access Database in whatever directory you run the executable from, it then creates a table in the database, adds some data to it, then dumps the data to the console - providing output all the way. Certainly there are C++ classes to wrap all this as Ancient Dragon mentioned, but I simply do it as this code shows.

Also, an only slightly modified version of this program will do the same thing with SQL Server.

This particular program was compiled with Dev C++, but also works with VC++ 6. I imagine with Code::Blocks too. You need to add references to the ODBC libs.

/*  MkDB.c  To get this working in DevC++ create a new C project in its own directory
    such as MkDB, then copy this file into a C source code file and name it Main.c.
    Then go to the 'Project' on the main menu and select 'Project Options'.  A tabbed
    dialog box will open and select the 'Parameters' tab.  The 'Linker' list box at the
    far right has a button under it  which when clicked will display an 'Open File'
    dialog box where you will have to navigate to the 'lib' directory.  It is a multi-
    file selection dialog box and you will have to select the libodbc32.a and the
    libodbccp32.a libraries.
*/
#include "windows.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "odbcinst.h"
#include "sql.h"
#include "sqlext.h"

typedef struct tagSQL
{
 SQLCHAR         szCnIn[512];
 SQLCHAR         szCnOut[512];
 short int       iBytes;
 SWORD           swStrLen;
 SQLHENV         hEnvr;
 SQLHDBC         hConn;
 unsigned int    blnConnected;
}SQL,*lpSql;

typedef struct tagDiagRec
{
 SQLINTEGER         iNativeErrPtr;
 SQLSMALLINT        iTextLenPtr;
 SQLCHAR            szErrMsg[512];
 SQLCHAR            szErrCode[8];
}DIAGNOSTICRECORD;


void ODBCConnect(SQLCHAR *szDB,lpSql sql)
{
 DIAGNOSTICRECORD dr;
 char lpBuffer[512];
 DWORD nBufLen=512;
 UINT iResult;

 SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&sql->hEnvr);
 SQLSetEnvAttr(sql->hEnvr,SQL_ATTR_ODBC_VERSION,(SQLPOINTER)SQL_OV_ODBC3,SQL_IS_INTEGER);
 SQLAllocHandle(SQL_HANDLE_DBC,sql->hEnvr,&sql->hConn);
 strcpy(sql->szCnIn,"DRIVER=Microsoft Access Driver (*.mdb);DBQ=");
 GetCurrentDirectory(nBufLen,lpBuffer);
 printf("lpBuffer=%s\n",lpBuffer);
 strcat(sql->szCnIn,lpBuffer);
 strcat(sql->szCnIn,"\\");
 strcat(sql->szCnIn,szDB);
 strcat(sql->szCnIn,";");
 printf("sql->szCnIn = %s\n",sql->szCnIn);
 iResult=
 SQLDriverConnect
 (
  sql->hConn,
  NULL,
  sql->szCnIn,
  (SQLSMALLINT)strlen(sql->szCnIn),
  sql->szCnOut,
  512,
  &sql->swStrLen,
  SQL_DRIVER_NOPROMPT
 );
 if(!iResult)
    sql->blnConnected=TRUE;
 else
 {
    SQLGetDiagRec
    (
      SQL_HANDLE_DBC,
      sql->hConn,
      1,
      dr.szErrCode,
      &dr.iNativeErrPtr,
      dr.szErrMsg,
      512,
      &dr.iTextLenPtr
    );
    printf("dr.szErrCode = %s\n",dr.szErrCode);
    printf("dr.szErrMsg  = %s\n",dr.szErrMsg);
    sql->blnConnected=FALSE;
    SQLDisconnect(sql->hConn);
    SQLFreeHandle(SQL_HANDLE_DBC ,sql->hConn);
    SQLFreeHandle(SQL_HANDLE_ENV,sql->hEnvr);
 }
}


void ODBCDisconnect(lpSql sql)
{
 SQLDisconnect(sql->hConn);
 SQLFreeHandle(SQL_HANDLE_DBC ,sql->hConn);
 SQLFreeHandle(SQL_HANDLE_ENV,sql->hEnvr);
}


void InstallerError(void)
{
 DWORD pErr;
 SQLCHAR szErrMsg[512];
 WORD cbMsgBuffer=512;
 WORD cbRet;
 WORD wErrNum=1;

 while(SQLInstallerError(wErrNum,&pErr,szErrMsg,cbMsgBuffer,&cbRet)!=SQL_NO_DATA)
 {
  printf("%u\t%u\t%s\n",wErrNum,pErr,szErrMsg);
  wErrNum++;
 };

 return;
}


UINT blnCreateDB(SQLCHAR *szDBName)
{
 SQLCHAR szCreate[24];

 printf("szDBName=%s\n",szDBName);
 strcpy(szCreate,"CREATE_DB=");
 strcat(szCreate,szDBName);
 printf("szCreate=%s\n",szCreate);
 if(SQLConfigDataSource(0,ODBC_ADD_DSN,"Microsoft Access-Treiber (*.mdb)",szCreate))
 {
    printf("SQLConfigDataSource() returned TRUE\n");
    return TRUE;
 }
 else
 {
    InstallerError();
    return FALSE;
 }
}


UINT blnMakeTable(lpSql sql)
{
 SQLCHAR szQuery[256];
 SQLHSTMT hStmt;

 strcpy(
 szQuery,
 "CREATE TABLE Table1 " \
 "(" \
   "Id LONG  NOT NULL PRIMARY KEY," \
   "Float_Point DOUBLE," \
   "Date_Field DATETIME," \
   "Text_Field CHAR(30)" \
 ");");
 printf("%s\n",szQuery);
 SQLAllocHandle(SQL_HANDLE_STMT,sql->hConn,&hStmt);
 if(SQLExecDirect(hStmt,szQuery,SQL_NTS)==0)
 {
    puts("Table1 Successfully Created!");
    SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
    return(TRUE);
 }
 else
 {
    puts("Table Creation Failure!");
    return(FALSE);
 }
}


TIMESTAMP_STRUCT ParseDate(SQLCHAR *szDate,SQLCHAR *szFormat,SQLCHAR *szDelimiter)
{
 UINT i=0,j=0,k=0;
 TIMESTAMP_STRUCT ts;
 SQLCHAR buf[3][8];          //buf[0] for month, buf[1] for day, buf[2] for year
 SQLCHAR *p;

 memset(buf,0,sizeof(buf));  //zero out buf[]
 p=szDate;
 for(i=0;i<strlen(szDate);i++)
 {
     if(*p!=*szDelimiter)
     {
        buf[j][k++]=*p;
        buf[j][k+1]='\0';
     }
     else
     {
        j++;
        k=0;
     }
     p++;
 }
 if(!strcmpi(szFormat,"MDY"))
 {
    ts.month=atoi(buf[0]);
    ts.day=atoi(buf[1]);
    ts.year=atoi(buf[2]);
 }
 if(!strcmpi(szFormat,"DMY"))
 {
    ts.day=atoi(buf[0]);
    ts.month=atoi(buf[1]);
    ts.year=atoi(buf[2]);
 }
 if(!strcmpi(szFormat,"YMD"))
 {
    ts.year=atoi(buf[0]);
    ts.month=atoi(buf[1]);
    ts.day=atoi(buf[2]);
 }

 return ts;
}


UINT blnInsert(lpSql sql)
{
 TIMESTAMP_STRUCT ts;
 DIAGNOSTICRECORD dr;
 SQLHSTMT         hStmt;
 SQLINTEGER       iJnk;
 SQLINTEGER       iNts=SQL_NTS;
 UINT             iId[]={1,2,3,4};
 double           dblNum[]={3.14159,1.23456,15.1234,0.54321};
 SQLCHAR          *szDate[]={"11/15/1952","6/30/1969","1/1/2006","4/1/2006"};
 SQLCHAR          *szStr[]={"My Birthday","Walk On Moon?","Some String","April Fools Day"};
 SQLCHAR          szQuery[100],szString[30];
 UINT             i,id,iRet=FALSE;
 double           dbl;

 if(SQLAllocHandle(SQL_HANDLE_STMT,sql->hConn,&hStmt)==SQL_SUCCESS)
 {
    strcpy(
    szQuery,
    "INSERT INTO Table1 " \
    "(" \
      "Id," \
      "Float_Point," \
      "Date_Field," \
      "Text_Field" \
    ") " \
    "VALUES(?,?,?,?);");
    printf("%s\n",szQuery);
    if(SQLPrepare(hStmt,szQuery,SQL_NTS)==SQL_SUCCESS)
    {
       SQLBindParameter(hStmt,1,SQL_PARAM_INPUT,SQL_C_LONG,SQL_INTEGER,0,0,&id,0,&iJnk);
       SQLBindParameter(hStmt,2,SQL_PARAM_INPUT,SQL_C_DOUBLE,SQL_DOUBLE,0,0,&dbl,0,&iJnk);
       SQLBindParameter(hStmt,3,SQL_PARAM_INPUT,SQL_C_TYPE_DATE,SQL_TYPE_DATE,0,0,&ts,0,&iJnk);
       SQLBindParameter(hStmt,4,SQL_PARAM_INPUT,SQL_C_CHAR,SQL_CHAR,29,0,szString,30,&iNts);
       printf("\n                                                         SQLExecute(hStmt)\n");
       printf("iId      Double           Date           String           0=SQL_SUCCESS  \n");
       printf("========================================================================\n");
       for(i=0;i<sizeof(iId)/sizeof(iId[0]);i++)
       {
           id=iId[i];dbl=dblNum[i];
           ts=ParseDate(szDate[i],"mdy","/");
           strcpy(szString,szStr[i]);
           if(SQLExecute(hStmt)==SQL_SUCCESS)
              printf("%u\t%f\t%s\t%s\t\t%u\n",id,dbl,szDate[i],szString,SQL_SUCCESS);
           else
           {
              SQLGetDiagRec
              (
                SQL_HANDLE_DBC,
                sql->hConn,
                1,
                dr.szErrCode,
                &dr.iNativeErrPtr,
                dr.szErrMsg,
                512,
                &dr.iTextLenPtr
              );
              printf("dr.szErrCode = %s\n",dr.szErrCode);
              printf("dr.szErrMsg  = %s\n",dr.szErrMsg);
              SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
              return FALSE;
           }
       }
       iRet=TRUE;
       printf("\n");
    }
    SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
 }

 return iRet;
}


SQLCHAR *MkDate(TIMESTAMP_STRUCT *ts)
{
 SQLCHAR szMonth[4],szDay[4],szYear[8];
 static  SQLCHAR szDate[12];

 sprintf(szMonth,"%u",ts->month);
 sprintf(szDay,"%u",ts->day);
 sprintf(szYear,"%u",ts->year);
 strcpy(szDate,szMonth);
 strcat(szDate,"/");
 strcat(szDate,szDay);
 strcat(szDate,"/");
 strcat(szDate,szYear);

 return szDate;
}


UINT blnDumpData(lpSql sql)
{
 SQLHSTMT          hStmt;
 SQLCHAR           szQuery[100];
 SQLINTEGER        iJnk;
 UINT              iId;
 double            dblNum;
 TIMESTAMP_STRUCT  ts;
 SQLCHAR           szString[30];

 if(SQLAllocHandle(SQL_HANDLE_STMT,sql->hConn,&hStmt)==SQL_SUCCESS)
 {
    strcpy(
    szQuery,
    "SELECT " \
      "Table1.Id," \
      "Table1.Float_Point," \
      "Table1.Date_Field," \
      "Table1.Text_Field " \
    "FROM " \
      "Table1;");
    printf("%s\n\n",(szQuery));
    SQLBindCol(hStmt,1,SQL_C_ULONG,&iId,0,&iJnk);
    SQLBindCol(hStmt,2,SQL_C_DOUBLE,&dblNum,0,&iJnk);
    SQLBindCol(hStmt,3,SQL_C_TYPE_DATE,&ts,0,&iJnk);
    SQLBindCol(hStmt,4,SQL_C_CHAR,szString,30,&iJnk);
    puts(" iId      Double           Date           String");
    puts("=====================================================");
    if(SQLExecDirect(hStmt,szQuery,SQL_NTS)==SQL_SUCCESS)
    {
       while(SQLFetch(hStmt)!=SQL_NO_DATA)
       {
        printf("%u\t%f\t%s\t%s\n",iId,dblNum,MkDate(&ts),szString);
       }
    }
    SQLCloseCursor(hStmt);
    SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
    return TRUE;
 }

 return FALSE;
}


int main(int argc, char *argv[])
{
 SQLCHAR szDBName[24];
 SQL sql;

 strcpy(szDBName,"TestData.mdb");
 if(blnCreateDB(szDBName))
 {
    ODBCConnect(szDBName,&sql);
    if(sql.blnConnected==TRUE)
    {
       puts("We're Connected!");
       if(blnMakeTable(&sql))
       {
          puts("Table1 Successfully Created!");
          if(blnInsert(&sql)==TRUE)
             printf("Data Insertion Successful!\n\n");
          else
             puts("Data Insertion Failure!");
          if(blnDumpData(&sql)==TRUE)
             puts("\nblnDumpData==TRUE");
          else
             puts("\nblnDumpData==FALSE");
       }
       else
          puts("Table Creation Failure!");
       ODBCDisconnect(&sql);
    }
    else
       puts("Connection Failure!");
 }
 else
    puts("Database Creation Failure!");
 system("PAUSE");

 return 0;
}

/*
szDBName=TestData.mdb
szCreate=CREATE_DB=TestData.mdb
SQLConfigDataSource() returned TRUE
lpBuffer=C:\Program Files\Microsoft Visual Studio\My Projects\MkDB\Release
sql->szCnIn = DSN=MS Access Database;DBQ=C:\Program Files\Microsoft Visual Studio\My Projects\MkDB\Rel
ease\TestData.mdb;DefaultDir=C:\Program Files\Microsoft Visual Studio\My Projects\MkDB\Release;DriverI
d=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;
We're Connected!
CREATE TABLE Table1 (Id LONG  NOT NULL PRIMARY KEY,Float_Point DOUBLE,Date_Field DATETIME,Text_Field C
HAR(30));
Table1 Successfully Created!
Table1 Successfully Created!
INSERT INTO Table1 (Id,Float_Point,Date_Field,Text_Field) VALUES(?,?,?,?);

                                                         SQLExecute(hStmt)
iId      Double           Date           String           0=SQL_SUCCESS
========================================================================
1       3.141590        11/15/1952      My Birthday             0
2       1.234560        6/30/1969       Walk On Moon?           0
3       15.123400       1/1/2006        Some String             0
4       0.543210        4/1/2006        April Fools Day         0

Data Insertion Successful!

SELECT Table1.Id,Table1.Float_Point,Table1.Date_Field,Table1.Text_Field FROM Table1;

 iId      Double           Date           String
=====================================================
1       3.141590        11/15/1952      My Birthday
2       1.234560        6/30/1969       Walk On Moon?
3       15.123400       1/1/2006        Some String
4       0.543210        4/1/2006        April Fools Day

blnDumpData==TRUE
Press any key to continue . . .
*/
Comments
Nice program :)

Thank you :))))a lot for your help .I want to ask a question about connect to sql with c++ .Except the devC++ how can I connect to sql in visual c++ for example connecting sql ,opening database and using some features as insert iupdate etc how can ı use all of these in visual situdio with the libraries of sql ?

If you plan to compile that code with VC++ 2008 then you will have to do a lot of typecasting from SQLCHAR to char*. Otherwise, works great.

Yea, I saw that about the type casting too. I fooled with it for about five minutes and didn't have time to finish it. I was thinking of wrapping that thing in classes, but just hadn't got around to it. Actually, I have a PowerBASIC GUI implementation of that where you click a button and the program creates an output window and prints everything to that window instead of a console window; but its posted in the PowerBASIC forums. Its straight Sdk code though.

Never was sure why the creators of the low level ODBC Api had to use those odd redifinitions of char.

Went through & changed all the SQLCHAR to char and that removed the need for 98% of the casting. Now, only the SQL function calls need cast. Anyway, here is a C++ version tested with VC++ 6 and with quite a few explanatory comments...

/*  MkDB.c  To get this working in DevC++ create a new C project in its own directory
    such as MkDB, then copy this file into a C source code file and name it Main.c.
    Then go to the 'Project' on the main menu and select 'Project Options'.  A tabbed
    dialog box will open and select the 'Parameters' tab.  The 'Linker' list box at the
    far right has a button under it  which when clicked will display an 'Open File'
    dialog box where you will have to navigate to the 'lib' directory.  It is a multi-
    file selection dialog box and you will have to select the libodbc32.a and the
    libodbccp32.a libraries.

    Tested with MS VC++ 6 8/4/2009 compiling as C++ with .cpp extension
*/

#include "windows.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "odbcinst.h"                  //Necessary to create access database
#include "sql.h"                       //ODBC header file
#include "sqlext.h"                    //ODBC header file

typedef struct tagSQL                  //This type helps with some 'grungy' initialization work
{                                      //in setting up an ODBC environment
 char            szCnIn[512];
 char            szCnOut[512];
 short int       iBytes;
 SWORD           swStrLen;
 SQLHENV         hEnvr;
 SQLHDBC         hConn;
 unsigned int    blnConnected;
}SQL,*lpSql;

typedef struct tagDiagRec              //ODBC functions return wonderful error information
{                                      //and this type helps in setting it up.  I have
 SQLINTEGER         iNativeErrPtr;     //found this the best way to do it, and  believe me, 
 SQLSMALLINT        iTextLenPtr;       //you need this error info!
 SQLCHAR            szErrMsg[512];
 SQLCHAR            szErrCode[8];
}DIAGNOSTICRECORD;


void ODBCConnect(char *szDB,lpSql sql) //Fairly forbidding stuff in here and you want to try
{                                      //to keep your application as isolated from it
 DIAGNOSTICRECORD dr;                  //as possible.  After you have the connection 
 char lpBuffer[512];                   //set up all you need is one function to get
 DWORD nBufLen=512;                    //a statement handle, 'SQLAllocHandle()' to use
 UINT iResult;                         //SQL statements to Select, Update, and Insert data

 SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&sql->hEnvr);
 SQLSetEnvAttr(sql->hEnvr,SQL_ATTR_ODBC_VERSION,(SQLPOINTER)SQL_OV_ODBC3,SQL_IS_INTEGER);
 SQLAllocHandle(SQL_HANDLE_DBC,sql->hEnvr,&sql->hConn);
 strcpy(sql->szCnIn,"DRIVER=Microsoft Access Driver (*.mdb);DBQ=");
 GetCurrentDirectory(nBufLen,lpBuffer);
 printf("lpBuffer=%s\n",lpBuffer);
 strcat(sql->szCnIn,lpBuffer);
 strcat(sql->szCnIn,"\\");
 strcat(sql->szCnIn,szDB);
 strcat(sql->szCnIn,";");
 printf("sql->szCnIn = %s\n",sql->szCnIn);
 iResult=
 SQLDriverConnect                      //this is the big, mean, ugly connection function
 (                                     //i.e., where the rubber meets the road.
  sql->hConn,                          //we just obtained sql->hConn above in last SQLAllocHandle() call
  NULL,                                //handle to a window is optional
  (SQLCHAR*)sql->szCnIn,               //here is the connection string we just built
  (SQLSMALLINT)strlen(sql->szCnIn),    //here it wants the length of the connection string
  (SQLCHAR*)sql->szCnOut,              //if the function succeeds it will return to us the Conn str it used
  512,                                 //this is the length of the output buffer for the Conn str 
  &sql->swStrLen,                      //this is the number of bytes it actually returned
  SQL_DRIVER_NOPROMPT                  //I'm telling it to fail rather than prompt me for more Conn info
 );
 if(!iResult)
    sql->blnConnected=TRUE;            //return TRUE through parameter if connection attempt was successful
 else
 {
    SQLGetDiagRec                      //if the connection attempt fails we'll call this function
    (                                  //to obtain an explanation for the failure
      SQL_HANDLE_DBC,
      sql->hConn,
      1,
      dr.szErrCode,
      &dr.iNativeErrPtr,
      dr.szErrMsg,
      512,
      &dr.iTextLenPtr
    );
    printf("dr.szErrCode = %s\n",dr.szErrCode);
    printf("dr.szErrMsg  = %s\n",dr.szErrMsg);
    sql->blnConnected=FALSE;
    SQLDisconnect(sql->hConn);
    SQLFreeHandle(SQL_HANDLE_DBC ,sql->hConn);
    SQLFreeHandle(SQL_HANDLE_ENV,sql->hEnvr);
 }
}


void ODBCDisconnect(lpSql sql)                 //Disconnect from data source, and
{                                              //release connection and environment 
 SQLDisconnect(sql->hConn);                    //handles
 SQLFreeHandle(SQL_HANDLE_DBC,sql->hConn);
 SQLFreeHandle(SQL_HANDLE_ENV,sql->hEnvr);
}


void InstallerError(void)
{
 DWORD pErr;
 char  szErrMsg[512];
 WORD  cbMsgBuffer=512;
 WORD  cbRet;
 WORD  wErrNum=1;

 while(SQLInstallerError(wErrNum,&pErr,szErrMsg,cbMsgBuffer,&cbRet)!=SQL_NO_DATA)
 {
  printf("%u\t%u\t%s\n",wErrNum,pErr,szErrMsg);
  wErrNum++;
 };

 return;
}


UINT blnCreateDB(char *szDBName)
{
 char szCreate[24];

 printf("szDBName=%s\n",szDBName);
 strcpy(szCreate,"CREATE_DB=");
 strcat(szCreate,szDBName);
 printf("szCreate=%s\n",szCreate);
 if(SQLConfigDataSource(0,ODBC_ADD_DSN,"Microsoft Access-Treiber (*.mdb)",szCreate))
 {
    printf("SQLConfigDataSource() returned TRUE\n");
    return TRUE;
 }
 else
 {
    InstallerError();
    return FALSE;
 }
}


UINT blnMakeTable(lpSql sql)          //Uses SQL Create Table statement to add table
{                                     //to database represented by sql->hConn
 char szQuery[256];
 SQLHSTMT hStmt;

 strcpy(
 szQuery,
 "CREATE TABLE Table1 " \
 "(" \
   "Id LONG  NOT NULL PRIMARY KEY," \
   "Float_Point DOUBLE," \
   "Date_Field DATETIME," \
   "Text_Field CHAR(30)" \
 ");");
 printf("%s\n",szQuery);
 SQLAllocHandle(SQL_HANDLE_STMT,sql->hConn,&hStmt);
 if(SQLExecDirect(hStmt,(SQLCHAR*)szQuery,SQL_NTS)==0)
 {
    puts("Table1 Successfully Created!");
    SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
    return(TRUE);
 }
 else
 {
    puts("Table Creation Failure!");
    return(FALSE);
 }
}


TIMESTAMP_STRUCT ParseDate(char* szDate, char* szFormat, char* szDelimiter)
{
 UINT i=0,j=0,k=0;
 TIMESTAMP_STRUCT ts;
 char buf[3][8];             //buf[0] for month, buf[1] for day, buf[2] for year
 char *p;

 memset(buf,0,sizeof(buf));  //zero out buf[]
 p=szDate;
 for(i=0;i<strlen((char*)szDate);i++)
 {
     if(*p!=*szDelimiter)
     {
        buf[j][k++]=*p;
        buf[j][k+1]='\0';
     }
     else
     {
        j++;
        k=0;
     }
     p++;
 }
 if(!strcmpi((char*)szFormat,"MDY"))
 {
    ts.month=atoi(buf[0]);
    ts.day=atoi(buf[1]);
    ts.year=atoi(buf[2]);
 }
 if(!strcmpi(szFormat,"DMY"))
 {
    ts.day=atoi(buf[0]);
    ts.month=atoi(buf[1]);
    ts.year=atoi(buf[2]);
 }
 if(!strcmpi(szFormat,"YMD"))
 {
    ts.year=atoi(buf[0]);
    ts.month=atoi(buf[1]);
    ts.day=atoi(buf[2]);
 }

 return ts;
}


UINT blnInsert(lpSql sql)
{
 TIMESTAMP_STRUCT ts;
 DIAGNOSTICRECORD dr;
 SQLHSTMT         hStmt;
 SQLINTEGER       iJnk;
 SQLINTEGER       iNts=SQL_NTS;
 UINT             iId[]={1,2,3,4};
 double           dblNum[]={3.14159,1.23456,15.1234,0.54321};
 char             *szDate[]={"11/15/1952","6/30/1969","1/1/2006","4/1/2006"};
 char             *szStr[]={"My Birthday","Walk On Moon?","Some String","April Fools Day"};
 char             szQuery[100],szString[30];
 UINT             i,id,iRet=FALSE;
 double           dbl;

 if(SQLAllocHandle(SQL_HANDLE_STMT,sql->hConn,&hStmt)==SQL_SUCCESS)
 {
    strcpy(
    (char*)szQuery,
    "INSERT INTO Table1 " \
    "(" \
      "Id," \
      "Float_Point," \
      "Date_Field," \
      "Text_Field" \
    ") " \
    "VALUES(?,?,?,?);");
    printf("%s\n",szQuery);
    if(SQLPrepare(hStmt,(SQLCHAR*)szQuery,SQL_NTS)==SQL_SUCCESS)
    {
       SQLBindParameter(hStmt,1,SQL_PARAM_INPUT,SQL_C_LONG,SQL_INTEGER,0,0,&id,0,&iJnk);
       SQLBindParameter(hStmt,2,SQL_PARAM_INPUT,SQL_C_DOUBLE,SQL_DOUBLE,0,0,&dbl,0,&iJnk);
       SQLBindParameter(hStmt,3,SQL_PARAM_INPUT,SQL_C_TYPE_DATE,SQL_TYPE_DATE,0,0,&ts,0,&iJnk);
       SQLBindParameter(hStmt,4,SQL_PARAM_INPUT,SQL_C_CHAR,SQL_CHAR,29,0,szString,30,&iNts);
       printf("\n                                                         SQLExecute(hStmt)\n");
       printf("iId      Double           Date           String           0=SQL_SUCCESS  \n");
       printf("========================================================================\n");
       for(i=0;i<sizeof(iId)/sizeof(iId[0]);i++)
       {
           id=iId[i];dbl=dblNum[i];
           ts=ParseDate(szDate[i],"mdy","/");
           strcpy(szString,szStr[i]);
           if(SQLExecute(hStmt)==SQL_SUCCESS)
              printf("%u\t%f\t%s\t%s\t\t%u\n",id,dbl,szDate[i],szString,SQL_SUCCESS);
           else
           {
              SQLGetDiagRec
              (
                SQL_HANDLE_DBC,
                sql->hConn,
                1,
                dr.szErrCode,
                &dr.iNativeErrPtr,
                dr.szErrMsg,
                512,
                &dr.iTextLenPtr
              );
              printf("dr.szErrCode = %s\n",dr.szErrCode);
              printf("dr.szErrMsg  = %s\n",dr.szErrMsg);
              SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
              return FALSE;
           }
       }
       iRet=TRUE;
       printf("\n");
    }
    SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
 }

 return iRet;
}


char* MkDate(TIMESTAMP_STRUCT *ts)
{
 char szMonth[4],szDay[4],szYear[8];
 static  char szDate[12];

 sprintf(szMonth,"%u",ts->month);
 sprintf(szDay,"%u",ts->day);
 sprintf(szYear,"%u",ts->year);
 strcpy(szDate,szMonth);
 strcat(szDate,"/");
 strcat(szDate,szDay);
 strcat(szDate,"/");
 strcat(szDate,szYear);

 return szDate;
}


UINT blnDumpData(lpSql sql)
{
 SQLHSTMT          hStmt;
 char              szQuery[100];
 SQLINTEGER        iJnk;
 UINT              iId;
 double            dblNum;
 TIMESTAMP_STRUCT  ts;
 SQLCHAR           szString[30];

 if(SQLAllocHandle(SQL_HANDLE_STMT,sql->hConn,&hStmt)==SQL_SUCCESS)
 {
    strcpy(
    szQuery,
    "SELECT " \
      "Table1.Id," \
      "Table1.Float_Point," \
      "Table1.Date_Field," \
      "Table1.Text_Field " \
    "FROM " \
      "Table1;");
    printf("%s\n\n",(szQuery));
    SQLBindCol(hStmt,1,SQL_C_ULONG,&iId,0,&iJnk);
    SQLBindCol(hStmt,2,SQL_C_DOUBLE,&dblNum,0,&iJnk);
    SQLBindCol(hStmt,3,SQL_C_TYPE_DATE,&ts,0,&iJnk);
    SQLBindCol(hStmt,4,SQL_C_CHAR,szString,30,&iJnk);
    puts(" iId      Double           Date           String");
    puts("=====================================================");
    if(SQLExecDirect(hStmt,(SQLCHAR*)szQuery,SQL_NTS)==SQL_SUCCESS)
    {
       while(SQLFetch(hStmt)!=SQL_NO_DATA)
       {
        printf("%u\t%f\t%s\t%s\n",iId,dblNum,MkDate(&ts),szString);
       }
    }
    SQLCloseCursor(hStmt);
    SQLFreeHandle(SQL_HANDLE_STMT,hStmt);
    return TRUE;
 }

 return FALSE;
}


int main(int argc, char *argv[])
{
 char szDBName[24];
 SQL sql;
 
 strcpy(szDBName,"TestData.mdb");
 if(blnCreateDB(szDBName))
 {
    ODBCConnect(szDBName,&sql);
    if(sql.blnConnected==TRUE)
    {
       puts("We're Connected!");
       if(blnMakeTable(&sql))
       {
          puts("Table1 Successfully Created!");
          if(blnInsert(&sql)==TRUE)
             printf("Data Insertion Successful!\n\n");
          else
             puts("Data Insertion Failure!");
          if(blnDumpData(&sql)==TRUE)
             puts("\nblnDumpData==TRUE");
          else
             puts("\nblnDumpData==FALSE");
       }
       else
          puts("Table Creation Failure!");
       ODBCDisconnect(&sql);
    }
    else
       puts("Connection Failure!");
 }
 else
    puts("Database Creation Failure!");
 system("PAUSE");

 return 0;
}

Never was sure why the creators of the low level ODBC Api had to use those odd redifinitions of char.

Probably because its platform and language independent. SQLCHAR might be defined as something other than unsigned char on other platforms or computer languages.

And there are already c++ wrappers.

This article has been dead for over six months. Start a new discussion instead.