Lovely
Upcoming SlideShare
Loading in...5
×
 

Lovely

on

  • 403 views

 

Statistics

Views

Total Views
403
Views on SlideShare
403
Embed Views
0

Actions

Likes
0
Downloads
1
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Lovely Lovely Document Transcript

  • 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 worlds 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 QueryLanguage.[8]The MySQL development project has made its source code available under the terms of the GNU GeneralPublic License, as well as under a variety of proprietary agreements. MySQL was owned and sponsored by asingle 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 whichuse MySQL databases include: TYPO3, Joomla, WordPress, phpBB, MyBB, Drupal and other software built onthe 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 intimidatingtask to the new software developer.Its 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 errorsSetting up Test Data in a MySQL DatabaseBefore a programmer can use a database that database must, of course, exist; or, at very least, a test databasemust 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 dataThe first step (logging on to MySQL) can be done from the command line:
  • mysql -u<user> -p<password> mysqlNext, 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, its time to start thinking about doing some actual programming.Creating a Stored Procedure in a MySQL DatabaseOne of the new additions to MySQL is one that Oracle users will already know - the stored function. The greatadvantage to using stored functions is that programming code can be built into the database rather than into anapplication - meaning that multiple applications can use the same piece of code:delimiter //create function user_count () returns intdeterministicbegindeclare 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 ofthe 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 DatabaseThis example code above will compile and run, but doesnt actually do anything - first the C++ code must makea 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 reasonC++ Code for Running a Query on a MySQL DatabaseHaving 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 QueryIf the connection is successful and the query returns a result (otherwise known as a recordset) then the next stepis 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 DatabaseThe 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++ CodeHow the code is compiled will depend on the operating system being used and the local set up - in the case ofDebian Linux the code would be compiled by using the command:g++ -o db db.cc -L/usr/include/mysql -lmysqlclient -I/usr/include/mysqlAssuming, of course, that the code is stored in a file named db.cc.ConclusionBoth the MySQL database and the C++ programming language are powerful tools in their own right; andcombined they are an incredibly important tool for the software developer - an important tool and one which isvery 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 theJDBC 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 thetable City using the Prepared Statements, demonstrates transactions using savepoints and examines the resultset and database metadata.The sample code is provided only for the purpose of demonstration. It does not recommend the readers to adopta 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 toconnect, 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 clientmachine. MySQL C++ Driver Based on JDBC 4.0 SpecificationMySQL Connector/C++ is one of the latest connectors for MySQL, developed by Sun Microsystems. The MySQLconnector for C++ provides an object-oriented application programming interface (API) and a database driverfor connecting C++ applications to the MySQL Server.The development of Connector/C++ took a different approach compared to the existing drivers for C++ byimplementing the JDBC API in C++ world. In other words, Connector/C++ drivers interface is mostly based onJava programming languages JDBC API. Java Database Connectivity (JDBC) API is the industry standard forconnectivity 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 arefamiliar with JDBC programming may find this useful, and as a result, it could improve applicationdevelopment time.The following classes were implemented by the MySQL Connector/C++. Driver Connection Statement PreparedStatement ResultSet Savepoint DatabaseMetaData ResultSetMetaData ParameterMetaDataThe 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 InstallationStarting with release 1.0.4, Connector/C++ is available in binary form for Solaris, Linux, Windows, FreeBSD, Mac OS X, HP-UX and AIXplatforms. MSI installer and a binary zip file without the installer is available for Windows, where as the binary package is availableas compressed GNU TAR archive (tar.gz) for the rest of the platforms. You can download the pre-compiled binary from theConnector/C++ download page.Installation from the binary package is very straight forward on Windows and other platforms - simply unpacking the archive in adesired location installs the Connector/C++ driver. Both statically linked and the dynamically linked Connector/C++ driver can befound in lib directory under the driver installation directory. If you plan to use the dynamically linked version of MySQLConnector/C++, ensure that the runtime linker can find the MySQL Client Library. Consult your operating system documentation forthe steps to modify and expand the search path for libraries. In case you cannot modify the library search path, copy yourapplication, the MySQL Connector/C++ driver and the MySQL Client Library into the same directory. This approach may work onmost of the platforms as they search the originating directory by default, before searching for the required dynamic librarieselsewhere.Source InstallationThose 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 flexibleprogramming language with a multi-platform and stable database; but this may seem an intimidating task to the newsoftware developer.
  • Its 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 errorsSetting up Test Data in a MySQL DatabaseBefore a programmer can use a database that database must, of course, exist; or, at very least, a test database mustexist. Fortunately creating a database in MySQL is very simple and consists of three steps:log on to MySQLuse SQL to create the MySQL database and any tablespopulate the tables with appropriate dataThe first step (logging on to MySQL) can be done from the command line:mysql -u<user> -p<password> mysqlNext, 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, its time to start thinking about doing some actual programming.Creating a Stored Procedure in a MySQL DatabaseOne of the new additions to MySQL is one that Oracle users will already know - the stored function. The great advantageto 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 intdeterministicbegindeclare 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 theprocess - 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 DatabaseThis example code above will compile and run, but doesnt actually do anything - first the C++ code must make aconnection 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 reasonC++ Code for Running a Query on a MySQL DatabaseHaving made a successful connection to the MySQL database the C++ code may be used to send s SQL query - in thiscase 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 QueryIf the connection is successful and the query returns a result (otherwise known as a recordset) then the next step is todisplay 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 DatabaseThe 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++ CodeHow the code is compiled will depend on the operating system being used and the local set up - in the case of DebianLinux the code would be compiled by using the command:g++ -o db db.cc -L/usr/include/mysql -lmysqlclient -I/usr/include/mysqlAssuming, of course, that the code is stored in a file named db.cc.ConclusionBoth the MySQL database and the C++ programming language are powerful tools in their own right; and combined theyare an incredibly important tool for the software developer - an important tool and one which is very easy to use, andvery, very effective. ASSIGNMENT: NOVEMER SANGUAL