Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Using MySQL Database with C
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