Solved

C program linking Access database file

Posted on 2001-06-16
7
1,890 Views
Last Modified: 2008-03-17
How can I link my C program to a microsoft Access database file(search,change,and add data)?What header

files do I have to include?Do you have a sample program? (Using traditional C rather than visual C).Actually,i'm using visual C++ compiler but i don't want to use the capabilities of that compiler.I want the basics that can be handeled by any compiler.
0
Comment
Question by:istiso
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 7

Expert Comment

by:KangaRoo
Comment Utility
Using ODBC.

There used to be an ODBC sdk available from microsoft, but they change their site all the time, so my links are always failing :(
And very likely it is already included with VC.
0
 

Author Comment

by:istiso
Comment Utility
it is important to know the exact header file.
0
 
LVL 7

Expert Comment

by:KangaRoo
Comment Utility
Try <sql.h> which declares ODBC core functions
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:istiso
Comment Utility
error C2146: syntax error : missing ';' before identifier 'SQLHWND'
0
 
LVL 10

Expert Comment

by:makerp
Comment Utility
i have gave this exmaple to a few people now, hope it helps

this is a simple example ive knocked up for you, create a simple access or sql server database and create
a system dsn for it in control panel. the open function uses global varaibles etc so you will probably
want to chage this.

/* 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));
         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 14

Expert Comment

by:AlexVirochovsky
Comment Utility
Other way see
http://www.1cplusplusstreet.com/xq/ASP/txtCodeId.1371/lngWId.3/qx/vb/scripts/ShowCode.htm

....
//**************************************
//    
// Name: Access MDB
// Description:To open MS Access or Ms S
//     QL server database using C/C++ or VC++
// By: Mokarrabin A Rahman
//
// Returns:Shows some recordsets
//
// Assumes:Change the name of the databa
//     se to any database and place it in the s
//     ame directory as the .exe. You shoul als
//     o change the SQL to your particular data
//     base. You may change the connect string
//     to connect to MS SQL Server.
//
// Side Effects:Great
//
//This code is copyrighted and has// limited warranties.Please see http://
//     www.1CPlusPlusStreet.com/xq/ASP/txtCodeI
//     d.1371/lngWId.3/qx/vb/scripts/ShowCode.h
//     tm//for details.//**************************************
//    

#import "c:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
// This code comes from : www.geocities.
//     com/mokarrabin
#include <stdio.h>
#include <iostream.h>
void main(void)


    {
    CoInitialize(NULL);
    try


        {
        _RecordsetPtr pRst("ADODB.Recordset");
        // Connection String
        _bstr_t strCnn("DRIVER={Microsoft Access Driver (*.mdb)};UID=admin;DBQ=GBOOK.mdb");
              // Open table
             pRst->Open("SELECT * FROM ProductService where ProductService like '%samir%';", strCnn, adOpenStatic, adLockReadOnly, adCmdText);
             
              pRst->MoveFirst();


                  while (!pRst->EndOfFile) {
                       cout<<(char*) ((_bstr_t) pRst->GetFields()->GetItem("ProductService")->GetValue())<<endl;
                       pRst->MoveNext();
                  }
                  pRst->Close();
                 
        }
        catch (_com_error &e)


            {
            cout<<(char*) e.Description();
        }
        ::CoUninitialize();
    }
....
alex

0
 
LVL 14

Accepted Solution

by:
AlexVirochovsky earned 50 total points
Comment Utility
No reaction, I hope, you solved your problems.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

763 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now