Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C++ MS Access connection!! any header/lib ??

Posted on 2001-07-09
9
Medium Priority
?
260 Views
Last Modified: 2007-12-19
hi all.
i wan to make a DB connection fron C/C++ to MS ACCESS.

Is there any header file/class libraries which does thsi.

I want to avoid MFC Classes 100 % and also the header or the Library should be free on net.
0
Comment
Question by:nefinjohn
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 10

Accepted Solution

by:
makerp earned 200 total points
ID: 6265156
you can use ODBC, heres an example

* for db stuff */
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <stdio.h>

HENV henv;
HDBC hdbc;
int dbopen=0;

/* opens a connection using global variables , bad i know */
#define PM_DSN "your_system_dsn"
#define PM_DSN_USER "your_db_username_if_any"
#define PM_DSN_PW "your_password_if_any"

int DBopen(void)
{
   int res=0;
   RETCODE retcode;
   /*allocate the environment handle*/
   if(SQLAllocEnv(&henv)==SQL_SUCCESS)
   {
        /*allocate the connection handle*/
        if(SQLAllocConnect(henv, &hdbc)==SQL_SUCCESS)
        {
             /* Set login timeout to 5 seconds. */
             SQLSetConnectOption(hdbc, SQL_LOGIN_TIMEOUT, 5);
             SQLSetConnectOption(hdbc, SQL_CURSOR_TYPE, SQL_CURSOR_STATIC);
             /* Connect to data source */
             retcode = SQLConnect(hdbc, PM_DSN, SQL_NTS, PM_DSN_USER, SQL_NTS, PM_DSN_PW, SQL_NTS);


             if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
             {
                       res=1;
                       DATABASE_NAME = getDBName();
             }
        }
        else
        {
             SQLFreeConnect(hdbc);
        }
   }
   else
   {
        SQLFreeEnv(henv);
   }
   dbopen=res;
   return res;
}

void DBclose(void)
{
   if(dbopen)
   {
        SQLDisconnect(hdbc);
        SQLFreeConnect(hdbc);
        SQLFreeEnv(henv);
        if(DATABASE_NAME)
        {
             free(DATABASE_NAME);
        }
   }
   dbopen=0;
}
int DBexecute(char *sql,HSTMT *hstmt)
{
   int res=0;
   RETCODE retcode;

   if(SQLAllocStmt(hdbc, hstmt)== SQL_SUCCESS)
   {
        retcode=SQLPrepare(*hstmt,sql,strlen(sql) + 1);
        if(retcode==SQL_SUCCESS)
        {
             retcode=SQLExecute(*hstmt);
             if(retcode==SQL_SUCCESS)
             {
                  res=1;
             }
        }
   }
   return res;
}

void DBcloseCursor(HSTMT hstmt)
{
   SQLFreeStmt(hstmt, SQL_DROP);
}

void main()
{
   char sql[255];
   HSTMT fstmt;
   long lens;
   RETCODE retcode;
   char name[100];

   DBopen();

   sprintf(sql,"SELECT name FROM users");
   if(DBexecute(sql,&fstmt))
   {      
        SQLBindCol(fstmt,1,SQL_C_CHAR, name,sizeof(name),&lens);
       
        retcode = SQLFetch(fstmt);    
        while(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
        {
             printf("%s\n",name);
             retcode = SQLFetch(fstmt);
        }
        DBcloseCursor(fstmt);
   }
   else
   {  
        printf("DBexecute failure : %s\n",getStmtError(fstmt));    
        exit(1);
   }
   DBclose();
}
0
 
LVL 10

Expert Comment

by:makerp
ID: 6265161
DATABASE_NAME = getDBName();

printf("DBexecute failure : %s\n",getStmtError(fstmt));    

remove those two lines as the functions they call are mssing and i can not find them

you will need to create a DSN to your database in ODBC control panel
0
 

Author Comment

by:nefinjohn
ID: 6267765
maherp !! hi !!
thanx for the respose.. from where can i get the above mentioned header files. is it free for download.

hey i am a beginner, c codes are really too long !!
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Expert Comment

by:sumansamanta
ID: 6267867
What is your compiler, is it MSVC++ ? If so, then ODBC library is there as a part of the kit. Here is a simple code that connects the BIBLIO.MDB file and fetches records from the Authors table ... Headers you must include to access ODBC APIs are sql.h,sqlext.h,tchar.h and ofcource windows.h. The runtime library is odbc32.lib.

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <sqlext.h>
#include <sql.h>
#include <tchar.h>
#include <stdlib.h>

//#define CONSTR          _T("DSN=oradsn;DRIVER=Oracle ODBC Driver;UID=test;PWD=test;")
#define CONSTR               _T("DSN=pubs;DRIVER=Microsoft Access Driver;UID=;PWD=;")
#define CONSTRLEN          sizeof(CONSTR) - 1

int main()
{
   SQLHENV       henv;
   SQLHDBC       hdbc;
   SQLHSTMT      hstmt;

   SQLTCHAR      szConnStrOut[1000];
   SQLSMALLINT   cbConnStrOutMax = 999;
   SQLSMALLINT   cbConnStrOut = 0;

   SQLTCHAR      szSqlStr[] = _T("select * from Authors"
                                     "where au_id < 10");
   SQLINTEGER    cbSqlStr = sizeof(szSqlStr) - 1;

   SQLINTEGER    nEmpid = 0;
   SQLCHAR       szName[51];
   SQLINTEGER    nYearBorn = 0;

   SQLINTEGER    cbSize = 0;
   int           nRows = 1;

   SQLRETURN     retcode;

   if ((retcode = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&henv)) ==  SQL_ERROR ) {
      printf("Could not initialize HENV ... \n");
      exit(0);
   }
   if ((retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0)) == SQL_ERROR ) {
      printf("Failed to set environment attributes . \n");
      SQLFreeHandle(SQL_HANDLE_ENV,henv);
      exit(0);
   }
   if ((retcode = SQLAllocHandle(SQL_HANDLE_DBC,henv,&hdbc)) == SQL_ERROR ) {
      printf("Could not initialize HDBC ... \n");
      SQLFreeHandle(SQL_HANDLE_ENV,henv);
      exit(0);
   }
   if ((retcode = SQLDriverConnect(hdbc,NULL,CONSTR,CONSTRLEN,szConnStrOut,cbConnStrOutMax,
&cbConnStrOut,SQL_DRIVER_NOPROMPT)) == SQL_ERROR ) {
      printf("Failed to connect ... \n");
      SQLFreeHandle(SQL_HANDLE_DBC,hdbc);
      SQLFreeHandle(SQL_HANDLE_ENV,henv);
      exit(0);
   }
   if ((retcode = SQLAllocHandle(SQL_HANDLE_STMT,hdbc,&hstmt)) == SQL_ERROR ) {
      printf("Failed to allocate HSTMT ... \n");
      SQLFreeHandle(SQL_HANDLE_DBC,hdbc);
      SQLFreeHandle(SQL_HANDLE_ENV,henv);
      exit(0);
   }
   if ((retcode = SQLPrepare(hstmt,szSqlStr,cbSqlStr)) == SQL_ERROR )
      printf("SQLPrepare() Failed ... \n");
   else
   {
      SQLBindCol(hstmt,1,SQL_C_LONG,&nEmpid,sizeof(SQL_C_LONG),&cbSize);
      SQLBindCol(hstmt,2,SQL_C_CHAR,szName,51,&cbSize);
      SQLBindCol(hstmt,3,SQL_C_LONG,&nYearBorn,sizeof(SQL_C_LONG),&cbSize);
      if ((retcode = SQLExecute(hstmt)) == SQL_ERROR)
         printf("SQLExecute() Failed ... \n");
      else {
         for(;;) {
            if ((retcode = SQLFetch(hstmt)) == SQL_NO_DATA)
            {
               printf("No more rows ... \n");
                break;
            } else {
               printf("Record No # %d\n",nRows++);
               printf("Au Id        = %d\n",nEmpid);
               printf("Au Name      = %s\n",szName);
               printf("Au Yr Born   = %d\n",nYearBorn);
               printf("-----------------------------n");
            }
         } /*End of for-loop*/
      }  
   }
   SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
   SQLFreeHandle(SQL_HANDLE_DBC,hdbc);
   SQLFreeHandle(SQL_HANDLE_ENV,henv);

   return(0);
}

In version 6.0 of VC++, The SQLAllocEnv() API is older, instead SQLAllocHandle() should be used. To get a detailed help seek MSDN, or visit www.microsoft.com for MSDN online.
0
 

Author Comment

by:nefinjohn
ID: 6267943
maherp !! hi !!
thanx for the respose.. from where can i get the above mentioned header files. is it free for download.

hey i am a beginner, c codes are really too long !!
0
 

Expert Comment

by:sumansamanta
ID: 6268112
What compiler are you using. Are you using Microsoft Visual C++ or Borland C++ or what ???
0
 
LVL 10

Expert Comment

by:makerp
ID: 6268224
use Miscrosoft VC++ and the headers are part of the install. if you cut and paste the code, remove the two lines as i suggested then create an appropriate access database, create a DSN to it, leave the username and password NULL,

#define PM_DSN "your_system_dsn"
#define PM_DSN_USER ""
#define PM_DSN_PW ""

then change the #defines to the above
0
 
LVL 11

Expert Comment

by:griessh
ID: 6825649
I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. Unless there is objection or further activity,  I will suggest to accept "makerp" comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points.
The link to the Community Support area is: http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner
0
 
LVL 5

Expert Comment

by:Netminder
ID: 6875095
Per recommendation comment force/accepted by

Netminder
Community Support Moderator
Experts Exchange
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

662 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question