SQL (Structured Query Language) is a fourth-generation language (4GL) that is used to define, manipulate, and control an RDBMS (relational database management system).
Before starting the main article, let us get familiar with the used tools.
-
Compiler: Code::Blocks IDE with MinGW compiler
Download Link: Binary Download
Code::Blocks is a cross compiler (It can run on any platform like Windows, Linux and Mac) and it is free to download. This IDE is specially designed for C and C++ and easy to use. -
API: We are going to use SQLAPI++ Library
Download Link: SQLAPI Download
SQLAPI++ is a C++ library (basically a set of header files) for accessing multiple SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL, SQLite, SQL Anywhere and ODBC). It is easy to implement and simple.
-
OCCI: Oracle C++ Call Interface
Download Link: OCCI C++ Download
OCCI is an interface defined by the database company ORACLE that defines a comfortable interfacefor the C++ programmer to access the Oracle database with classes using parameters that are reminiscent of SQL statements. The interface exists for ORACLE 9i, ORACLE 10 and comes with the Oracle.
We must download and install the above three (if we don’t have them). Now we are almost ready to start.
Some settings before starting:
-> Open the code::blocks IDE and go to or click on settings -> compiler and debugger settings (You will now see global compiler settings)
-> Now click on “Linker settings” in the linker settings click on ADD button and add the following
For Windows OS :
Code:
C:\SQLAPI\lib\libsqlapiddll.a
C:\Program Files\CodeBlocks\MinGW\lib\libuser32.a
C:\Program Files\CodeBlocks\MinGW\lib\libversion.a
C:\Program Files\CodeBlocks\MinGW\lib\liboleaut32.a
C:\Program Files\CodeBlocks\MinGW\lib\libole32.a
These will be found in your SQLAPI++ (If you have not extracted in C: drive then select the appropriate location and add the mentioned files to linker settings).
The above code is used to add library files to connect C/C++ program with SQLAPI.
Basically, there are 2 steps:
- Connecting to database (and error handling)
Code:// C++ pgroram for connecting to database (and error handling)#include<stdio.h>#include<SQLAPI.h> // main SQLAPI++ headerintmain(intargc,char* argv[]){// create connection object to connect to databaseSAConnection con;try{// connect to database// in this example, it is Oracle,// but can also be Sybase, Informix, DB2// SQLServer, InterBase, SQLBase and ODBCcon.Connect ("test",// database name"tester",// user name"tester",// passwordSA_Oracle_Client);//Oracle Clientprintf("We are connected!\n");// Disconnect is optional// autodisconnect will occur in destructor if neededcon.Disconnect();printf("We are disconnected!\n");}catch(SAException & x){// SAConnection::Rollback()// can also throw an exception// (if a network error for example),// we will be readytry{// on error rollback changescon.Rollback ();}catch(SAException &){}// print error messageprintf("%s\n", (constchar*)x.ErrText());}return0;}chevron_rightfilter_noneOutput:
We are Connected! We are Disconnected!
- Executing a simple SQL Command
Now, we will look out to execute a simple SQL query.Firstly, creating a table for the database:create table tb1(id number, name varchar(20);
Now, establish the connection to the database then, after your con.connect; method you should use cmd.setCommandText method to pass the query to the database, it is as shown below:
con.Connect("test", "tester", "tester", SA_Oracle_Client); cmd.setCommandText("create table tb1(id number, name varchar(20));”);and now, to execute the query we have to use the following command:
cmd.Execute();
Full Code:
#include<stdio.h>#include <SQLAPI.h> // main SQLAPI++ headerintmain(intargc,char* argv[]){SAConnection con;// connection object to connect to databaseSACommandcmd;// create command objecttry{// connect to database (Oracle in our example)con.Connect("test","tester","tester", SA_Oracle_Client);// associate a command with connection// connection can also be specified in SACommand constructorcmd.setConnection(&con;);// create tablecmd.setCommandText("create table tbl(id number, name varchar(20));");cmd.Execute();// insert valuecmd.setCommandText("Insert into tbl(id, name) values (1,”Vinay”)");cmd.setCommandText("Insert into tbl(id, name) values (2,”Kushal”)");cmd.setCommandText("Insert into tbl(id, name) values (3,”Saransh”)");cmd.Execute();// commit changes on successcon.Commit();printf("Table created, row inserted!\n");}catch(SAException &x;){// SAConnection::Rollback()// can also throw an exception// (if a network error for example),// we will be readytry{// on error rollback changescon.Rollback();}catch(SAException &){}// print error messageprintf("%s\n", (constchar*)x.ErrText());}return0;}chevron_rightfilter_none
As we know, Oracle is not auto committed (committing is making permanent reflection of data in the database) so, we have to commit it.
con.Commit();
and similarly we can roll back the transactions when an exception occurs, so to do that we use:
con.Rollback();
For deleting a row, we use this command.
cmd.setCommandText("delete from tb1 where id= 2");
Thus, by the end of this article, we have learned how to connect your C/C++ program to database and perform manipulations.
This article is contributed by Vinay Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Create a database on Relational Database Service (RDS) of Amazon Web Services(AWS)
- PHP program to fetch data from localhost server database using XAMPP
- How and Why To Create an SQL Database on Azure
- Database Connection and Queries in Codeigniter
- Apache Cassandra (NOSQL database)
- Top 7 Database You Must Know For Software Development Projects
- Top 5 Free, Cross-Platform, and Open-Source Database System in 2020
- Print pattern using only one loop | Set 1 (Using setw)
- Count number of unique Triangles using STL | Set 1 (Using set)
- How will you print numbers from 1 to 100 without using loop?
- Write a C program to print "Geeks for Geeks" without using a semicolon
- How to print % using printf()?
- Print "Even" or "Odd" without using conditional statement
- How to deallocate memory without using free() in C?
- To find sum of two numbers without using any operator
- Can we access private data members of a class without using a member or a friend function?
- Print a long int in C using putchar() only
- Print substring of a given string without using any string function and loop in C
- How to make a website using WordPress (Part - 1)
- How to make a website using WordPress (Part – 2)

