C / C++ FAQs & Programming Resources - ProkutFAQ : HowToConnectDatabase

HomePage Recent Changes Recently Commented Login/Register

How can we connect/access databases using C/C++ ?

There are no standard libraries in C or C++ for handling Databases. However, each of the database system comes with their own libraries for C and C++, and there are numerous libraries available which can enable you to write cross-platform database applications. Also, most of the modern compilers provide libraries to have easy connectivity to most of the popular database systems.

DBMS Libraries for C


MySQL C API
MySQL provides C language APIs for communicating with MySQL databases. These APIs are platform independant and comes with the MySQL setup package. For more information on how to use these APIs, read their reference manual which can be found at:http://dev.mysql.com/doc/refman/5.0/en/c.html

DBMS Libraries for C++

SOCI - The C++ Database Access Library
SOCI is an open-source database access library for C++ which can be used with MCVC++ and GCC compilers. This library lets you embed the SQL queries in C++ code using the regular C++ code style. It supports Oracle, MySQL and PostgreSQL databases. You can find documentation, examples, and more information from their project website.

SQLAPI++ Library
SQLAP++ provides C++ APIs which can be used to access different databases, such as Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL and ODBC. You can find more information and links to download the library from: http://www.sqlapi.com/

MySQL++
MySQL++ provides C++ wrapper classes for C API's of MySQL database. More information can be found on their website at:
http://tangentsoft.net/mysql++/

OTL
OTL is a platform independent database library. It covers the functionality of a whole database API with just a handful of concrete classes and several template PL/SQL (Oracle) table container classes. The OTL code gets expanded into direct database API function calls, so it provides ultimate performance, reliability and thread safety in multi-processor environments as well as traditional batch programs. It supports Oracle 7 (natively via OCI7), Oracle 8 (natively via OCI8), Oracle 8i (natively via OCI8i), Oracle 9i (natively via OCI9i), Oracle 10g (natively via OCI10g), DB2 (natively via DB2 CLI), ODBC 3.x as well as ODBC 2.5 compliant data sources in MS Windows and Unix (e.g. Oracle, MS SQL Server, Sybase, Informix, MySQL, DB2, Interbase / Firebird, PostgreSQL, SQLite, SAP/DB, TimesTen, MS ACCESS, etc.). The list of supported database backends is constantly growing.



Code examples


MySQL
Below is an example of connecting and querying an MySQL Database, courtesy: Delbrooks's post in C community thread.
#include <stdio.h>
/*The MySQL library header file*/
#include <mysql.h>
/*#define the database details such as the host, the username, the password, and the database to connect to*/
#define host "localhost"
#define username "root"
#define password "123456"
#define database "testdb"
/*You will have to change the values in the quotes to match the values that fit your database details. */

/*The next line creates a pointer of type MYSQL to the active database connection:*/
MYSQL *conn;

int main()
{

    MYSQL_RES *res_set;
    MYSQL_ROW row;
    /*Followed by that, we tell mySQL that are are about to connect with the mysql_init() function.
    We pass a value of NULL to it because for our purposes, we don't need to go into it any further:*/

    conn = mysql_init(NULL);

    if( conn == NULL )
    {
        printf("Failed to initate MySQL\n");
        return 1;
    }

    /*The next step is to actually connect to the database. This is where the conn variable and the host,
    username, password, and database #define's are used:*/

    if( ! mysql_real_connect(conn,host,username,password,database,0,NULL,0) )
    {
        printf( "Error connecting to database: %s\n", mysql_error(conn));
        return 1;
    }

    unsigned int i;

    /*Finally, we query the database with the following query using the mysql_query() function: "SELECT * FROM users" like so:*/
    mysql_query(conn,"SELECT name, email, password FROM users");

    /*After querying the result, we need to store the result data in the variable res_set we defined earlier. This is done like so:*/
    res_set = mysql_store_result(conn);

    /*In our example, there will most likely be more than one row returned (i.e., if there are more than one user in
    the users table of the database). If so, then you need to find how many rows are returned so that you can
    loop through each one and print the result of each one like so:*/

    unsigned int numrows = mysql_num_rows(res_set);
    unsigned int num_fields = mysql_num_fields(res_set);


    /*Finally, we retrive the result using the function mysql_fetch_row() and then print out all of the data in large chunks.
    This is done like so:*/

    while ((row = mysql_fetch_row(res_set)) != NULL)
    {

        for(i = 0; i < num_fields; i++)
        {
             printf("%s\t", row[i] ? row[i] : "NULL");
        }
        printf("\n");

    }

    /*Last but certainly not least, we close our connection to the database*/
    mysql_close(conn);
    return 0;

}


Here is an MSDN link on how to connect to an Oracle database using VC++:
http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/dnaroledbp/html/msdn_ole4orcl.asp

Below is an example code on how to connect to Sybase using C on UNIX flavors:
/* Anyone who understands this code, please edit this page and add comments*/
#include<iostream.h>
#include<sybfront.h>
#include<sybdb.h>
int main()
{
    DBPROCESS *dbproc;
    LOGINREC *login;
    DBCHAR name1[15];
    DBINT no1;
    RETCODE ret_code;
    fflush(stdout);
    dbinit();
    login=dblogin();
    DBSETLUSER(login,<Login name>);
    DBSETLPWD(login,<Password>);
    dbproc=dbopen(login,NULL);
    dbcmd(dbproc,"select * from table");
    dbsqlexec(dbproc);
    return 0;
}


Connecting to Database using Turbo C/C++

If you have a 16 bit compiler like Turbo C/C++ for DOS, then you have no way to access any database as there are no libraries supporting that compiler. You will need to upgrade to newer and modern compilers like MSVC++ or GCC. See our Free compilers section to find and download compilers..

Related Links

ODBC from C Tutorial by Easysoft.

 Comments [Hide comments/form]
Well,doubtlessly its a very helpful document for most programmers .
can you please help me how to do connection with MS Access using C++ code.Currently i'm using MS Visual Studio 2005 as my editor.
U can send your solution or guidance to my mail ID- www.pkj.litu@gmail.com
Please help me soon
-- softexinc.com (2009-01-02 11:36:37)
tnx for giving us info about turbo c..
it helps us alot!!
-- acl1-1648bts.gw.smartbro.net (2009-07-11 05:18:26)
useful one
-- 117.193.135.79 (2009-07-29 22:01:56)
Hi this is a pretty cool example to connect... I have just one problem: I get the following error messages, don't know why! Do you have a solution for it?
undefined reference to '_mysql_init@4'
undefined reference to '_mysql_real_connect@32'
undefined reference to '_mysql_close@4'
I have started learning c++ about a month ago.
-- wblv-ip-pcache-7-vif1.telkom-ipnet.co.za (2009-08-06 14:37:51)
You need to link the MySQL library (libmysql.lib file) to your program. Linking method depends on your compiler, so you'd have to tell us which compiler/IDE are you using to get more help.
-- SharathAV (2009-08-09 14:33:28)
send me the sql command used to list all the active hosts connected with sql server.......and give me explaination for the above program briefly with every datatypes and words used in it............................my mail id : ben.06feb@gmail.com
-- dsl-tn-dynamic-159.247.164.122.airtelbroadband.in (2010-06-02 10:54:46)
thx...its really gud
-- 220.227.5.242 (2010-06-05 09:19:38)
i am using dev cpp and open cv
i want to establish databse connection using c.
how can i do it?
please give details !!
-- 117.199.162.0 (2010-06-11 10:27:33)
Hi ..This is a real helpful document..I am an oracle developer and my project requires c++ to be connected to Oracle whenever data is needed. Could anyone please help me out in this. If you hav got any docs plz sent to evanceheally@yahoo.co.in
-- 19963142252.honeywell.com (2010-08-10 09:35:27)
I got it....
ThankS God
-- exch-del.ind.aptaracorp.com (2012-04-15 08:24:35)
thanksssssssssssssss
-- 10.0.0.164 (2012-08-04 11:45:10)
Page was generated in -0.9260 seconds