SlideShare a Scribd company logo
Assignment in CPR
                             -Lovely Mae D. Marindoque-
MySQL ( /maɪ ˌ skjuˌ ɛ l/ "My S-Q-L",[4] officially, but also called /maɪ ˌ kwəl/ "My Sequel") is
                    ɛ        ˌ                                               siˌ
the world's most used open source relational database management system (RDBMS)[6] that runs as a server
                     [5]

providing multi-user access to a number of databases.

It is named after co-founder Michael Widenius' daughter, My.[7] The SQL phrase stands for Structured Query
Language.[8]

The MySQL development project has made its source code available under the terms of the GNU General
Public License, as well as under a variety of proprietary agreements. MySQL was owned and sponsored by a
single for-profit firm, the Swedish company MySQL AB, now owned by Oracle Corporation.[9]

Free-software-open source projects that require a full-featured database management system often use MySQL.
For commercial use, several paid editions are available, and offer additional functionality. Applications which
use MySQL databases include: TYPO3, Joomla, WordPress, phpBB, MyBB, Drupal and other software built on
the LAMP software stack. MySQL is also used in many high-profile, large-scale World Wide Web products,
including Wikipedia, Google[10] (though not for searches), Facebook,[11] and Twitter.[12]




                      Using a MySQL Database with C++
C++ and MySQL are both very powerful, but when combined they can make a killer application.

One of the most powerful combinations that any programmer can use is the combination of C++ and MySQL -
a flexible programming language with a multi-platform and stable database; but this may seem an intimidating
task to the new software developer.

It's not. This article will show just how easy it is for a programmer to use C++ to:

       set up a connection to a MySQL database
       use the C++ code to access an MySQL stored function
       display the results returned by the MySQL stored function
       and (perhaps most importantly) handle any errors

Setting up Test Data in a MySQL Database

Before a programmer can use a database that database must, of course, exist; or, at very least, a test database
must exist. Fortunately creating a database in MySQL is very simple and consists of three steps:

   1. log on to MySQL
   2. use SQL to create the MySQL database and any tables
   3. populate the tables with appropriate data

The first step (logging on to MySQL) can be done from the command line:
mysql -u<user> -p<password> mysql

Next, simple SQL can be used to the database and tables for the database:

create database cpp_data;
use cpp_data;
create table users(id int, fname varchar(25), sname varchar(25), active bool);
insert into users values (1, 'Fred', 'Smith', True);
insert into users values (2, 'Jane', 'Jones', True);

With this done, it's time to start thinking about doing some actual programming.

Creating a Stored Procedure in a MySQL Database

One of the new additions to MySQL is one that Oracle users will already know - the stored function. The great
advantage to using stored functions is that programming code can be built into the database rather than into an
application - meaning that multiple applications can use the same piece of code:

delimiter //

create function user_count () returns int

deterministic

begin

declare c int;

select count(*) into c from users where active = True;

return c;

end

//

delimiter ;

This code simply returns the number of active users (from the table users).

Loading the MySQL Header File into C++

When using MySQL with C++ the programmer needs to know absolutely nothing about the actual mechanics of
the process - all the programmer has to do is to load the MySQL header file:

#include <iostream>

#include <mysql.h>

using namespace std;

MYSQL *connection, mysql;

MYSQL_RES *result;
MYSQL_ROW row;

int query_state;

int main() {

return 0;

}

C++ Code for Connecting to a Database

This example code above will compile and run, but doesn't actually do anything - first the C++ code must make
a connection to the MySQL database:

mysql_init(&mysql);

//connection = mysql_real_connect(&mysql,"host","user","password","database",0,0,0);

connection = mysql_real_connect(&mysql,"localhost","bainm","not_telling","cpp_data",0,0,0);

if (connection == NULL) {

cout << mysql_error(&mysql) << endl;

return 1;

}

The above code:

        initialises the MySQL connection
        makes the connection to the MySQL database (for which the programmer needs to define the host, user name,
        password and database)
        displays an error message if the connection is rejected for any reason

C++ Code for Running a Query on a MySQL Database

Having made a successful connection to the MySQL database the C++ code may be used to send s SQL query -
in this case to run the stored procedure created earlier:

query_state = mysql_query(connection, "select user_count()");

if (query_state !=0) {

cout << mysql_error(connection) << endl;

return 1;

}

This time the C++ code sends the SQL and then displays another error message if any problem is encountered.
C++ Code for Processing the Results of a MySQL Query

If the connection is successful and the query returns a result (otherwise known as a recordset) then the next step
is to display those results:

result = mysql_store_result(connection);

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

cout << row[0] << endl;

}

C++ Code for Disconnecting from a MySQL Database

The final step is to free up any memory used by the recordset and to close the connection:

mysql_free_result(result);

mysql_close(connection);

Compiling and Running the C++ Code

How the code is compiled will depend on the operating system being used and the local set up - in the case of
Debian Linux the code would be compiled by using the command:

g++ -o db db.cc -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql

Assuming, of course, that the code is stored in a file named db.cc.

Conclusion

Both the MySQL database and the C++ programming language are powerful tools in their own right; and
combined they are an incredibly important tool for the software developer - an important tool and one which is
very easy to use, and very, very effective.

Testing the MySQL Database Connectivity With the Connector/C++

The following C++ code sample demonstrates how to connect to a MySQL Server running on the same host,
using the MySQL Connector for C++. The code sample connects to the MySQL database test by using the
JDBC like API provided by the Connector C++, executes a query to retrieve all the rows from the table City,
extracts the data from the result set and displays it on the standard output, inserts couple of rows of data into the
table City using the Prepared Statements, demonstrates transactions using savepoints and examines the result
set and database metadata.

The sample code is provided only for the purpose of demonstration. It does not recommend the readers to adopt
a particular style of coding. To keep it simple, the sample code assumes that the user always provides well-
formed input - hence there is no explicit error checking code in the following example. Use discretion in re-
using the sample code
Using a MySQL Database with C++
This tutorial will show you the essential steps to build and install MySQL Connector/C++ driver, with simple examples to
connect, insert, and retrieve data from a MySQL database. Because the focus is on database connectivity from a C++
application, this document assumes that some kind of MySQL database is already up and accessible from the client
machine.
                             MySQL C++ Driver Based on JDBC 4.0 Specification
MySQL Connector/C++ is one of the latest connectors for MySQL, developed by Sun Microsystems. The MySQL
connector for C++ provides an object-oriented application programming interface (API) and a database driver
for connecting C++ applications to the MySQL Server.
The development of Connector/C++ took a different approach compared to the existing drivers for C++ by
implementing the JDBC API in C++ world. In other words, Connector/C++ driver's interface is mostly based on
Java programming language's JDBC API. Java Database Connectivity (JDBC) API is the industry standard for
connectivity between the Java programming language and a wide range of databases. Connector/C++
implemented a significant percentage of the JDBC 4.0 specification. C++ application developers who are
familiar with JDBC programming may find this useful, and as a result, it could improve application
development time.
The following classes were implemented by the MySQL Connector/C++.
         Driver
         Connection
         Statement
         PreparedStatement
         ResultSet
         Savepoint
         DatabaseMetaData
         ResultSetMetaData
         ParameterMetaData
The Connector/C++ driver can be used to connect to MySQL 5.1 and later versions.
Prior to MySQL Connector/C++, C++ application developers were required to use either the non-standard &
procedural MySQL C API directly or the MySQL++ API, which is a C++ wrapper for the MySQL C API.
                                            Installing MySQL Connector/C++
Binary Installation
Starting with release 1.0.4, Connector/C++ is available in binary form for Solaris, Linux, Windows, FreeBSD, Mac OS X, HP-UX and AIX
platforms. MSI installer and a binary zip file without the installer is available for Windows, where as the binary package is available
as compressed GNU TAR archive (tar.gz) for the rest of the platforms. You can download the pre-compiled binary from the
Connector/C++ download page.
Installation from the binary package is very straight forward on Windows and other platforms - simply unpacking the archive in a
desired location installs the Connector/C++ driver. Both statically linked and the dynamically linked Connector/C++ driver can be
found in lib directory under the driver installation directory. If you plan to use the dynamically linked version of MySQL
Connector/C++, ensure that the runtime linker can find the MySQL Client Library. Consult your operating system documentation for
the steps to modify and expand the search path for libraries. In case you cannot modify the library search path, copy your
application, the MySQL Connector/C++ driver and the MySQL Client Library into the same directory. This approach may work on
most of the platforms as they search the originating directory by default, before searching for the required dynamic libraries
elsewhere.
Source Installation
Those who want to build the connector driver from the source code, please check the Installing MySQL Connector/C++
from Source page for detailed instructions.
C++ and MySQL are both very powerful, but when combined they can make a killer application.

One of the most powerful combinations that any programmer can use is the combination of C++ and MySQL - a flexible
programming language with a multi-platform and stable database; but this may seem an intimidating task to the new
software developer.
It's not. This article will show just how easy it is for a programmer to use C++ to:
          returned by the MySQL stored function
          and (perhaps most set up a connection to a MySQL database
          use the C++ code to access an MySQL stored function
          display the results importantly) handle any errors

Setting up Test Data in a MySQL Database
Before a programmer can use a database that database must, of course, exist; or, at very least, a test database must
exist. Fortunately creating a database in MySQL is very simple and consists of three steps:
log on to MySQL
use SQL to create the MySQL database and any tables
populate the tables with appropriate data
The first step (logging on to MySQL) can be done from the command line:
mysql -u<user> -p<password> mysql
Next, simple SQL can be used to the database and tables for the database:
create database cpp_data;
use cpp_data;
create table users(id int, fname varchar(25), sname varchar(25), active bool);
insert into users values (1, 'Fred', 'Smith', True);
insert into users values (2, 'Jane', 'Jones', True);

With this done, it's time to start thinking about doing some actual programming.

Creating a Stored Procedure in a MySQL Database
One of the new additions to MySQL is one that Oracle users will already know - the stored function. The great advantage
to using stored functions is that programming code can be built into the database rather than into an application -
meaning that multiple applications can use the same piece of code:
delimiter //
create function user_count () returns int
deterministic
begin
declare c int;
select count(*) into c from users where active = True;
return c;
end
//
delimiter ;
This code simply returns the number of active users (from the table users).

Loading the MySQL Header File into C++
When using MySQL with C++ the programmer needs to know absolutely nothing about the actual mechanics of the
process - all the programmer has to do is to load the MySQL header file:
#include <iostream>
#include <mysql.h>
using namespace std;
MYSQL *connection, mysql;
MYSQL_RES *result;
MYSQL_ROW row;
int query_state;
int main() {
return 0;
}
C++ Code for Connecting to a Database
This example code above will compile and run, but doesn't actually do anything - first the C++ code must make a
connection to the MySQL database:
mysql_init(&mysql);
//connection = mysql_real_connect(&mysql,"host","user","password","database",0,0,0);
connection = mysql_real_connect(&mysql,"localhost","bainm","not_telling","cpp_data",0,0,0);
if (connection == NULL) {
cout << mysql_error(&mysql) << endl;
return 1;
}
The above code:
        initialises the MySQL connection
        makes the connection to the MySQL database (for which the programmer needs to define the host, user name,
        password and database)
        displays an error message if the connection is rejected for any reason

C++ Code for Running a Query on a MySQL Database
Having made a successful connection to the MySQL database the C++ code may be used to send s SQL query - in this
case to run the stored procedure created earlier:
query_state = mysql_query(connection, "select user_count()");
if (query_state !=0) {
cout << mysql_error(connection) << endl;
return 1;
}
This time the C++ code sends the SQL and then displays another error message if any problem is encountered.

C++ Code for Processing the Results of a MySQL Query
If the connection is successful and the query returns a result (otherwise known as a recordset) then the next step is to
display those results:
result = mysql_store_result(connection);
while ( ( row = mysql_fetch_row(result)) != NULL ) {
cout << row[0] << endl;
}

C++ Code for Disconnecting from a MySQL Database
The final step is to free up any memory used by the recordset and to close the connection:
mysql_free_result(result);
mysql_close(connection);

Compiling and Running the C++ Code
How the code is compiled will depend on the operating system being used and the local set up - in the case of Debian
Linux the code would be compiled by using the command:
g++ -o db db.cc -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql
Assuming, of course, that the code is stored in a file named db.cc.

Conclusion
Both the MySQL database and the C++ programming language are powerful tools in their own right; and combined they
are an incredibly important tool for the software developer - an important tool and one which is very easy to use, and
very, very effective.
                                                                                                       ASSIGNMENT:
                                                                                              NOVEMER SANGUAL

More Related Content

PDF
Docker Java App with MariaDB – Deployment in Less than a Minute
dchq
 
PDF
MySQL docker with demo by Ramana Yeruva
Mysql User Camp
 
PPT
Mysqlppt3510
Khan Rahimeen
 
PPT
Web Server(Apache),
webhostingguy
 
PDF
APACHE WEB SERVER FOR LINUX
webhostingguy
 
PPT
Apache Web Server Setup 2
Information Technology
 
PPT
]project-open[ Package Manager
Klaus Hofeditz
 
PDF
Configuring the Apache Web Server
webhostingguy
 
Docker Java App with MariaDB – Deployment in Less than a Minute
dchq
 
MySQL docker with demo by Ramana Yeruva
Mysql User Camp
 
Mysqlppt3510
Khan Rahimeen
 
Web Server(Apache),
webhostingguy
 
APACHE WEB SERVER FOR LINUX
webhostingguy
 
Apache Web Server Setup 2
Information Technology
 
]project-open[ Package Manager
Klaus Hofeditz
 
Configuring the Apache Web Server
webhostingguy
 

What's hot (8)

PPT
]project-open[ CVS+ACL Permission Configuration
Klaus Hofeditz
 
PPTX
Web server installation_configuration_apache
Shaojie Yang
 
PPTX
Apache web server
zrstoppe
 
PPTX
Presentation
Joel Kurian
 
PPT
Apache Web Server Architecture Chaitanya Kulkarni
webhostingguy
 
PPT
Apache Ppt
Hema Prasanth
 
PPT
Apache
Rathan Raj
 
PDF
Mysql tutorial 5257
Phuong Do Anh
 
]project-open[ CVS+ACL Permission Configuration
Klaus Hofeditz
 
Web server installation_configuration_apache
Shaojie Yang
 
Apache web server
zrstoppe
 
Presentation
Joel Kurian
 
Apache Web Server Architecture Chaitanya Kulkarni
webhostingguy
 
Apache Ppt
Hema Prasanth
 
Apache
Rathan Raj
 
Mysql tutorial 5257
Phuong Do Anh
 
Ad

Similar to Lovely (20)

PDF
Interface python with sql database.pdf--
jagaspeed09
 
PDF
Interface python with sql database.pdf
MohammadImran709594
 
PDF
Node.js with MySQL.pdf
SudhanshiBakre1
 
PDF
Interface python with sql database10.pdf
HiteshNandi
 
PDF
SULTHAN's PHP, MySQL & wordpress
SULTHAN BASHA
 
PPT
My sql basic
Prabhat gangwar
 
PPT
Slides
webhostingguy
 
PPTX
Connecting to my sql using PHP
Nisa Soomro
 
PDF
MySQL on Docker and Kubernetes
Balasubramanian Kandasamy
 
PPT
Mysqlppt3510
Anuja Lad
 
PPT
Mysql
guest817344
 
PDF
Www Kitebird Com Articles Pydbapi Html Toc 1
AkramWaseem
 
PPTX
Interfacing python to mysql (11363255151).pptx
cavicav231
 
ODP
Sql installation
Balakumaran Arunachalam
 
PDF
Why Do I Need Mysql for A Website....pdf
Shattered Silicon
 
PDF
My First 100 days with a MySQL DBMS (WP)
Gustavo Rene Antunez
 
PDF
Mysql tutorial
Pankaj Sipl
 
PDF
Midwest PHP Presentation - New MSQL Features
Dave Stokes
 
PDF
MySQL Cluster 8.0 tutorial
Frazer Clement
 
PPT
Mysql ppt
Sanmuga Nathan
 
Interface python with sql database.pdf--
jagaspeed09
 
Interface python with sql database.pdf
MohammadImran709594
 
Node.js with MySQL.pdf
SudhanshiBakre1
 
Interface python with sql database10.pdf
HiteshNandi
 
SULTHAN's PHP, MySQL & wordpress
SULTHAN BASHA
 
My sql basic
Prabhat gangwar
 
Connecting to my sql using PHP
Nisa Soomro
 
MySQL on Docker and Kubernetes
Balasubramanian Kandasamy
 
Mysqlppt3510
Anuja Lad
 
Www Kitebird Com Articles Pydbapi Html Toc 1
AkramWaseem
 
Interfacing python to mysql (11363255151).pptx
cavicav231
 
Sql installation
Balakumaran Arunachalam
 
Why Do I Need Mysql for A Website....pdf
Shattered Silicon
 
My First 100 days with a MySQL DBMS (WP)
Gustavo Rene Antunez
 
Mysql tutorial
Pankaj Sipl
 
Midwest PHP Presentation - New MSQL Features
Dave Stokes
 
MySQL Cluster 8.0 tutorial
Frazer Clement
 
Mysql ppt
Sanmuga Nathan
 
Ad

Recently uploaded (20)

PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Architecture of the Future (09152021)
EdwardMeyman
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 

Lovely

  • 1. Assignment in CPR -Lovely Mae D. Marindoque- MySQL ( /maɪ ˌ skjuˌ ɛ l/ "My S-Q-L",[4] officially, but also called /maɪ ˌ kwəl/ "My Sequel") is ɛ ˌ siˌ the world's most used open source relational database management system (RDBMS)[6] that runs as a server [5] providing multi-user access to a number of databases. It is named after co-founder Michael Widenius' daughter, My.[7] The SQL phrase stands for Structured Query Language.[8] The MySQL development project has made its source code available under the terms of the GNU General Public License, as well as under a variety of proprietary agreements. MySQL was owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now owned by Oracle Corporation.[9] Free-software-open source projects that require a full-featured database management system often use MySQL. For commercial use, several paid editions are available, and offer additional functionality. Applications which use MySQL databases include: TYPO3, Joomla, WordPress, phpBB, MyBB, Drupal and other software built on the LAMP software stack. MySQL is also used in many high-profile, large-scale World Wide Web products, including Wikipedia, Google[10] (though not for searches), Facebook,[11] and Twitter.[12] Using a MySQL Database with C++ C++ and MySQL are both very powerful, but when combined they can make a killer application. One of the most powerful combinations that any programmer can use is the combination of C++ and MySQL - a flexible programming language with a multi-platform and stable database; but this may seem an intimidating task to the new software developer. It's not. This article will show just how easy it is for a programmer to use C++ to: set up a connection to a MySQL database use the C++ code to access an MySQL stored function display the results returned by the MySQL stored function and (perhaps most importantly) handle any errors Setting up Test Data in a MySQL Database Before a programmer can use a database that database must, of course, exist; or, at very least, a test database must exist. Fortunately creating a database in MySQL is very simple and consists of three steps: 1. log on to MySQL 2. use SQL to create the MySQL database and any tables 3. populate the tables with appropriate data The first step (logging on to MySQL) can be done from the command line:
  • 2. mysql -u<user> -p<password> mysql Next, simple SQL can be used to the database and tables for the database: create database cpp_data; use cpp_data; create table users(id int, fname varchar(25), sname varchar(25), active bool); insert into users values (1, 'Fred', 'Smith', True); insert into users values (2, 'Jane', 'Jones', True); With this done, it's time to start thinking about doing some actual programming. Creating a Stored Procedure in a MySQL Database One of the new additions to MySQL is one that Oracle users will already know - the stored function. The great advantage to using stored functions is that programming code can be built into the database rather than into an application - meaning that multiple applications can use the same piece of code: delimiter // create function user_count () returns int deterministic begin declare c int; select count(*) into c from users where active = True; return c; end // delimiter ; This code simply returns the number of active users (from the table users). Loading the MySQL Header File into C++ When using MySQL with C++ the programmer needs to know absolutely nothing about the actual mechanics of the process - all the programmer has to do is to load the MySQL header file: #include <iostream> #include <mysql.h> using namespace std; MYSQL *connection, mysql; MYSQL_RES *result;
  • 3. MYSQL_ROW row; int query_state; int main() { return 0; } C++ Code for Connecting to a Database This example code above will compile and run, but doesn't actually do anything - first the C++ code must make a connection to the MySQL database: mysql_init(&mysql); //connection = mysql_real_connect(&mysql,"host","user","password","database",0,0,0); connection = mysql_real_connect(&mysql,"localhost","bainm","not_telling","cpp_data",0,0,0); if (connection == NULL) { cout << mysql_error(&mysql) << endl; return 1; } The above code: initialises the MySQL connection makes the connection to the MySQL database (for which the programmer needs to define the host, user name, password and database) displays an error message if the connection is rejected for any reason C++ Code for Running a Query on a MySQL Database Having made a successful connection to the MySQL database the C++ code may be used to send s SQL query - in this case to run the stored procedure created earlier: query_state = mysql_query(connection, "select user_count()"); if (query_state !=0) { cout << mysql_error(connection) << endl; return 1; } This time the C++ code sends the SQL and then displays another error message if any problem is encountered.
  • 4. C++ Code for Processing the Results of a MySQL Query If the connection is successful and the query returns a result (otherwise known as a recordset) then the next step is to display those results: result = mysql_store_result(connection); while ( ( row = mysql_fetch_row(result)) != NULL ) { cout << row[0] << endl; } C++ Code for Disconnecting from a MySQL Database The final step is to free up any memory used by the recordset and to close the connection: mysql_free_result(result); mysql_close(connection); Compiling and Running the C++ Code How the code is compiled will depend on the operating system being used and the local set up - in the case of Debian Linux the code would be compiled by using the command: g++ -o db db.cc -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql Assuming, of course, that the code is stored in a file named db.cc. Conclusion Both the MySQL database and the C++ programming language are powerful tools in their own right; and combined they are an incredibly important tool for the software developer - an important tool and one which is very easy to use, and very, very effective. Testing the MySQL Database Connectivity With the Connector/C++ The following C++ code sample demonstrates how to connect to a MySQL Server running on the same host, using the MySQL Connector for C++. The code sample connects to the MySQL database test by using the JDBC like API provided by the Connector C++, executes a query to retrieve all the rows from the table City, extracts the data from the result set and displays it on the standard output, inserts couple of rows of data into the table City using the Prepared Statements, demonstrates transactions using savepoints and examines the result set and database metadata. The sample code is provided only for the purpose of demonstration. It does not recommend the readers to adopt a particular style of coding. To keep it simple, the sample code assumes that the user always provides well- formed input - hence there is no explicit error checking code in the following example. Use discretion in re- using the sample code
  • 5. Using a MySQL Database with C++ This tutorial will show you the essential steps to build and install MySQL Connector/C++ driver, with simple examples to connect, insert, and retrieve data from a MySQL database. Because the focus is on database connectivity from a C++ application, this document assumes that some kind of MySQL database is already up and accessible from the client machine. MySQL C++ Driver Based on JDBC 4.0 Specification MySQL Connector/C++ is one of the latest connectors for MySQL, developed by Sun Microsystems. The MySQL connector for C++ provides an object-oriented application programming interface (API) and a database driver for connecting C++ applications to the MySQL Server. The development of Connector/C++ took a different approach compared to the existing drivers for C++ by implementing the JDBC API in C++ world. In other words, Connector/C++ driver's interface is mostly based on Java programming language's JDBC API. Java Database Connectivity (JDBC) API is the industry standard for connectivity between the Java programming language and a wide range of databases. Connector/C++ implemented a significant percentage of the JDBC 4.0 specification. C++ application developers who are familiar with JDBC programming may find this useful, and as a result, it could improve application development time. The following classes were implemented by the MySQL Connector/C++. Driver Connection Statement PreparedStatement ResultSet Savepoint DatabaseMetaData ResultSetMetaData ParameterMetaData The Connector/C++ driver can be used to connect to MySQL 5.1 and later versions. Prior to MySQL Connector/C++, C++ application developers were required to use either the non-standard & procedural MySQL C API directly or the MySQL++ API, which is a C++ wrapper for the MySQL C API. Installing MySQL Connector/C++ Binary Installation Starting with release 1.0.4, Connector/C++ is available in binary form for Solaris, Linux, Windows, FreeBSD, Mac OS X, HP-UX and AIX platforms. MSI installer and a binary zip file without the installer is available for Windows, where as the binary package is available as compressed GNU TAR archive (tar.gz) for the rest of the platforms. You can download the pre-compiled binary from the Connector/C++ download page. Installation from the binary package is very straight forward on Windows and other platforms - simply unpacking the archive in a desired location installs the Connector/C++ driver. Both statically linked and the dynamically linked Connector/C++ driver can be found in lib directory under the driver installation directory. If you plan to use the dynamically linked version of MySQL Connector/C++, ensure that the runtime linker can find the MySQL Client Library. Consult your operating system documentation for the steps to modify and expand the search path for libraries. In case you cannot modify the library search path, copy your application, the MySQL Connector/C++ driver and the MySQL Client Library into the same directory. This approach may work on most of the platforms as they search the originating directory by default, before searching for the required dynamic libraries elsewhere. Source Installation Those who want to build the connector driver from the source code, please check the Installing MySQL Connector/C++ from Source page for detailed instructions. C++ and MySQL are both very powerful, but when combined they can make a killer application. One of the most powerful combinations that any programmer can use is the combination of C++ and MySQL - a flexible programming language with a multi-platform and stable database; but this may seem an intimidating task to the new software developer.
  • 6. It's not. This article will show just how easy it is for a programmer to use C++ to: returned by the MySQL stored function and (perhaps most set up a connection to a MySQL database use the C++ code to access an MySQL stored function display the results importantly) handle any errors Setting up Test Data in a MySQL Database Before a programmer can use a database that database must, of course, exist; or, at very least, a test database must exist. Fortunately creating a database in MySQL is very simple and consists of three steps: log on to MySQL use SQL to create the MySQL database and any tables populate the tables with appropriate data The first step (logging on to MySQL) can be done from the command line: mysql -u<user> -p<password> mysql Next, simple SQL can be used to the database and tables for the database: create database cpp_data; use cpp_data; create table users(id int, fname varchar(25), sname varchar(25), active bool); insert into users values (1, 'Fred', 'Smith', True); insert into users values (2, 'Jane', 'Jones', True); With this done, it's time to start thinking about doing some actual programming. Creating a Stored Procedure in a MySQL Database One of the new additions to MySQL is one that Oracle users will already know - the stored function. The great advantage to using stored functions is that programming code can be built into the database rather than into an application - meaning that multiple applications can use the same piece of code: delimiter // create function user_count () returns int deterministic begin declare c int; select count(*) into c from users where active = True; return c; end // delimiter ; This code simply returns the number of active users (from the table users). Loading the MySQL Header File into C++ When using MySQL with C++ the programmer needs to know absolutely nothing about the actual mechanics of the process - all the programmer has to do is to load the MySQL header file: #include <iostream> #include <mysql.h> using namespace std; MYSQL *connection, mysql; MYSQL_RES *result; MYSQL_ROW row; int query_state; int main() { return 0; }
  • 7. C++ Code for Connecting to a Database This example code above will compile and run, but doesn't actually do anything - first the C++ code must make a connection to the MySQL database: mysql_init(&mysql); //connection = mysql_real_connect(&mysql,"host","user","password","database",0,0,0); connection = mysql_real_connect(&mysql,"localhost","bainm","not_telling","cpp_data",0,0,0); if (connection == NULL) { cout << mysql_error(&mysql) << endl; return 1; } The above code: initialises the MySQL connection makes the connection to the MySQL database (for which the programmer needs to define the host, user name, password and database) displays an error message if the connection is rejected for any reason C++ Code for Running a Query on a MySQL Database Having made a successful connection to the MySQL database the C++ code may be used to send s SQL query - in this case to run the stored procedure created earlier: query_state = mysql_query(connection, "select user_count()"); if (query_state !=0) { cout << mysql_error(connection) << endl; return 1; } This time the C++ code sends the SQL and then displays another error message if any problem is encountered. C++ Code for Processing the Results of a MySQL Query If the connection is successful and the query returns a result (otherwise known as a recordset) then the next step is to display those results: result = mysql_store_result(connection); while ( ( row = mysql_fetch_row(result)) != NULL ) { cout << row[0] << endl; } C++ Code for Disconnecting from a MySQL Database The final step is to free up any memory used by the recordset and to close the connection: mysql_free_result(result); mysql_close(connection); Compiling and Running the C++ Code How the code is compiled will depend on the operating system being used and the local set up - in the case of Debian Linux the code would be compiled by using the command: g++ -o db db.cc -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql Assuming, of course, that the code is stored in a file named db.cc. Conclusion Both the MySQL database and the C++ programming language are powerful tools in their own right; and combined they are an incredibly important tool for the software developer - an important tool and one which is very easy to use, and very, very effective. ASSIGNMENT: NOVEMER SANGUAL