SlideShare ist ein Scribd-Unternehmen logo
1 von 7
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

Weitere ähnliche Inhalte

Was ist angesagt?

]project-open[ CVS+ACL Permission Configuration
]project-open[ CVS+ACL Permission Configuration]project-open[ CVS+ACL Permission Configuration
]project-open[ CVS+ACL Permission ConfigurationKlaus Hofeditz
 
Web server installation_configuration_apache
Web server installation_configuration_apacheWeb server installation_configuration_apache
Web server installation_configuration_apacheShaojie Yang
 
Apache web server
Apache web serverApache web server
Apache web serverzrstoppe
 
Apache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya KulkarniApache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya Kulkarniwebhostingguy
 

Was ist angesagt? (8)

]project-open[ CVS+ACL Permission Configuration
]project-open[ CVS+ACL Permission Configuration]project-open[ CVS+ACL Permission Configuration
]project-open[ CVS+ACL Permission Configuration
 
Web server installation_configuration_apache
Web server installation_configuration_apacheWeb server installation_configuration_apache
Web server installation_configuration_apache
 
Apache web server
Apache web serverApache web server
Apache web server
 
Presentation
PresentationPresentation
Presentation
 
Apache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya KulkarniApache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya Kulkarni
 
Apache Ppt
Apache PptApache Ppt
Apache Ppt
 
Apache
ApacheApache
Apache
 
Mysql tutorial 5257
Mysql tutorial 5257Mysql tutorial 5257
Mysql tutorial 5257
 

Ähnlich wie Using MySQL Database with C

Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdfMohammadImran709594
 
Interface python with sql database10.pdf
Interface python with sql database10.pdfInterface python with sql database10.pdf
Interface python with sql database10.pdfHiteshNandi
 
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpressSULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpressSULTHAN BASHA
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHPNisa Soomro
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510Anuja Lad
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1AkramWaseem
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxcavicav231
 
My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)Gustavo Rene Antunez
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesDave Stokes
 
MySQL Cluster 8.0 tutorial
MySQL Cluster 8.0 tutorialMySQL Cluster 8.0 tutorial
MySQL Cluster 8.0 tutorialFrazer Clement
 
My sql università di enna a.a. 2005-06
My sql   università di enna a.a. 2005-06My sql   università di enna a.a. 2005-06
My sql università di enna a.a. 2005-06YUCHENG HU
 
Confoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New FeaturesConfoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New FeaturesDave Stokes
 

Ähnlich wie Using MySQL Database with C (20)

Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
Interface python with sql database10.pdf
Interface python with sql database10.pdfInterface python with sql database10.pdf
Interface python with sql database10.pdf
 
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpressSULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
 
My sql basic
My sql basicMy sql basic
My sql basic
 
Slides
SlidesSlides
Slides
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHP
 
MySQL on Docker and Kubernetes
MySQL on Docker and KubernetesMySQL on Docker and Kubernetes
MySQL on Docker and Kubernetes
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510
 
Mysql
MysqlMysql
Mysql
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
 
Sql installation
Sql installationSql installation
Sql installation
 
My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)
 
Mysql tutorial
Mysql tutorialMysql tutorial
Mysql tutorial
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL Features
 
MySQL Cluster 8.0 tutorial
MySQL Cluster 8.0 tutorialMySQL Cluster 8.0 tutorial
MySQL Cluster 8.0 tutorial
 
Mysql ppt
Mysql pptMysql ppt
Mysql ppt
 
My sql università di enna a.a. 2005-06
My sql   università di enna a.a. 2005-06My sql   università di enna a.a. 2005-06
My sql università di enna a.a. 2005-06
 
Confoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New FeaturesConfoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New Features
 

Kürzlich hochgeladen

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Kürzlich hochgeladen (20)

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
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