cbsecsnip-logo                         cbse-syllabus
cbse 100%
An online library for CBSE Computer Science and Informatics Practices students

How to Connect MySQl Database with C++ Print Friendly Version of this pagePrint Get a PDF version of this webpagePDF

Hi Friends,

Once again I came up with an uncommon tutorial for all C++ admirers. In this tutorial I will show you “How to connect and use MySQL database from your C++ Project” step by step. Basically we use flat file for saving record, when we are doing this from C++, which can also be done in MySQL.
As I already mentioned the reason why we should not use Turbo C/C++ for these type of work, in my one of the previous tutorial “how to use Excel from C++ program”, please read for it for detail other facts.
Before I proceed with my tutorial, you must be prepared with your development environment with some perquisites, assuming you are using Windows 7 OS you have to install following software (if required) –

So now you are ready to start with the tutorial.
Step 1: Create database in MySQL (here student is name of database)
Step 2: Create table (here personaldetail is name of table)
personaldetail

Column

Type

Null

Default

Comments

st_id

int(5)

No 

 

 Admission number of student

st_name

varchar(30)

No 

 

 Name of student

st_phone

varchar(12)

No 

 

 Phone number of student


Step 3: Open Code::Blocks and start a new Console Application C++ project
Step 4: Setting up Header files in Code::Blocks IDE
     a. From Projects window select your Project and right click on it then select Build Option…
MySQLCPP0

     b. From Project Build Option window select Debug which you will get under your project name in left pane.
     c. Click on Search Directories Tab and set the path of Include folder under SQLAPI folder which you installed at the beginning of this tutorial, my path “C:\SQLAPI\include “. (Don’t make path relative)

MySQLcpp1

Now click on Linker setting and select following files in following sequence – (Don’t make path relative)
  1. C:\SQLAPI\MinGW-4.4\lib\libsqlapiddll.a<\li>
  2. C:\Program Files\CodeBlocks\MinGW\lib\libuser32.a<\li>
  3. C:\Program Files\CodeBlocks\MinGW\lib\libversion.a<\li>
  4. C:\Program Files\CodeBlocks\MinGW\lib\liboleaut32.a<\li>
  5. C:\Program Files\CodeBlocks\MinGW\lib\libole32.a<\li>
MySQLcpp2

Step 5: Finally click OK when done with these settings.
Step 6: Now go to Compiler and debugger…  option from Setting Menu in main menu bar
Check your C++ compiler, Linker for dynamic libs, Debugger, Resource compiler and Make program file settings as shown in the following figure –

MySQLcpp3

Step 7: Copy these two .dll files “C:\SQLAPI\MinGW-4.4\bin\libsqlapid.dll” and “C:\Program Files\MySQL\MySQL Server 5.5\liblibmysql.dll”  in your application debug folder. My application folder is C:\msqldb\Mydata\bin\Debug

Finally here you completed all the settings we require to compile, debug, link, and dynamically link all the required files with your C++ application.
Step 8: Write the code in your main.cpp file as given below code is self explanatory –

 #include <iostream>
 #include <conio.h>
 #include <SQLAPI.h> //  main SQLAPI++ header
 using namespace std;
 int main(int argc, char*  argv[])
 {
   SAConnection con;   // create connection object
   SACommand cmd(&con,"Select st_id,  st_name, st_phone from personaldetail");      // create command object
   try
   {
      // connect to MySQL database
      con.Connect(
      "hotel",  // database name change as per your database  name
      "root",   // user name change per your setting
      "",       // password I don't have any password  for my database
      SA_MySQL_Client);
      cout<<"We are  connected!\n";
      // Select from our test table
      cmd.Execute();
      // fetch results row by row and print  results
      int i=0;
      while(cmd.FetchNext())
      {
          i++;
          cout<<"Row  "<<i<<" ";
          cout<<cmd.Field("st_id").asLong()<<" ";
          cout<<(const  char*)cmd.Field("st_name").asString()<<" ";
          cout<<(const  char*)cmd.Field("st_phone").asString()<<" ";
          cout<<endl;
      }
     // commit changes on success
     con.Commit();
     cout<<"Rows  selected!\n";
// Disconnect is optional // autodisconnect will ocur in destructor if needed con.Disconnect(); cout<<"We are disconnected!\n"; getch(); } catch(SAException &x) { // SAConnection::Rollback() // can also throw an exception // (if a network error for example), // we will be ready try { // on error rollback changes con.Rollback(); } catch(SAException &) { } // print error message cout<<(const char*)x.ErrText(); } return 0; }
Now build and run the project, if everything is well then you will see the records of your table, like this –

MySQLcpp4

We can do lot of more operations but I expect this is enough to show the way How to use MySQL database using C++ program. Further you read the online documentation given here http://www.sqlapi.com/. You can register in our Forum.

Regards
Vishal Deb
Author
Copyright © 2012, cbsecsnip.in | | Disclaimer | Terms of Service | Privacy Policy
login