Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Let'S Explore Mysql Connector/C++: Giri Mandalika

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Let's Explore

MySQL Connector/C++
Giri Mandalika
Software Engineer
Sun Microsystems, Inc.

1
Agenda
• What is MySQL Connector/C++?
• High Level Architecture
• Installation, Dependencies
• Implemented Classes
• Transactions
• Stored Procedures
• Exceptions
• Debug Tracing

2
MySQL Connector/C++
• C++ API and database driver for MySQL connectivity
• Wrapper around C-API
• Follows JDBC 4.0
• Advantages
> Convenience of pure C++ -- no C function calls
> JDBC 4.0 like API
> Easy to learn & use
• Supported Platforms
> Solaris, Linux, Windows, Mac, FreeBSD, HP-UX, AIX

3
High Level Architecture

Client Application
C++ API
MySQL Connector/C++
C API
MySQL Client Library
Client/Server
Protocol
MySQL Server DB

4
Installation
• Pre-built binary
• Build from source
> Build-time dependencies
– CMake
2.6.2 on Windows
2.4.2 on rest of the platforms

– MySQL Client Programming Support


MySQL Connector/C 6.0.1 [OR]
MySQL Server 5.1

5
Building & Installing Connector/C++
Example:

export CC=cc
export CXX=CC
export CFLAGS=-xO4
export CXXFLAGS=-xO4

cmake -DCMAKE_INSTALL_PREFIX=/path/to/connector/c++ \
-DCMAKE_BUILD_TYPE=Debug \
-DMYSQL_CONFIG_EXECUTABLE=/path/to/mysql_config \
-DMYSQLCPPCONN_TRACE_ENABLE:BOOL=1

make
make install

6
Dependencies, Compilers, Tools
• Runtime Dependencies
> MySQL Client Programming Support
> MySQL Connector/C++ driver

• Compilers
> GCC, Sun Studio, Visual Studio

• IDEs
> NetBeans, Visual Studio

7
Available Classes

Driver

Connection

Statement PreparedStatement Savepoint DatabaseMetaData

ResultSet ParameterMetaData

ResultSetMetaData

8
Establishing a Database Connection
Example:

#include <mysql_driver.h>
#include <cppconn/connection.h>
using namespace sql;
Driver *driver;
Connection *con;

try {
driver = mysql::get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306/test",
"dummy", "dummy");
} catch (..) {}

9
Connect String (Connection URL) Syntax

TCP/IP: tcp://[hostname[:port]][/schema]
UNIX Domain Socket: unix://path/to/unix_socket_file
Named Pipes: pipe://path/to/the/pipe

Example Connection URLs:


tcp://127.0.0.1:5555/test
unix:///tmp/mysql.sock
pipe://MySQL

10
Executing Queries using Statement Object
Example:
Connection *con;
Statement *stmt;
ResultSet *rs;
int updCnt;
bool retval;
stmt = con -> createStatement();
rs = stmt -> executeQuery ("SELECT .. ");
updCnt = stmt -> executeUpdate ("INSERT INTO .. ");
retval = stmt -> execute ("SELECT .. ");
if (retval) {
rs = stmt -> getResultSet();
} else {
updCnt = stmt -> getUpdateCount();
}

11
Prepared Statements
Example:

using namespace std;


Connection *con;
PreparedStatement *prep_stmt;
string Query ("INSERT INTO City (CityName) VALUES (?)");

prep_stmt = con -> prepareStatement (Query);


prep_stmt -> setString (1, "London, UK");
int updatecount = prep_stmt -> executeUpdate();
prep_stmt -> clearParameters();

12
Result Sets

Example:

Statement *stmt;
ResultSet *rs;

rs = stmt -> executeQuery ("SELECT CityName FROM City");


while (rs -> next()) {
cout << rs -> getString("CityName") << endl;
}

13
Buffered Vs Unbuffered Result Sets
Example:

Statement *stmt;
ResultSet *rs;

/* Buffered Results */
rs = stmt->setResultSetType(ResultSetType::TYPE_SCROLL_INSENSITIVE)
-> executeQuery(..);

/* Unbuffered Results */
rs = stmt ->setResultSetType(ResultSetType::TYPE_FORWARD_ONLY)
-> executeQuery(..);

14
Result Set Meta Data

Example:

PreparedStatement *prep_stmt;
ResultSet *rs;
ResultSetMetaData *rs_meta, *ps_rs_meta;

rs_meta = rs -> getMetaData();


cout << "Number of Columns: " << rs_meta -> getColumnCount();
//delete res_meta; /* this statement won't work */

prep_stmt = con -> prepareStatement ("SELECT CityName from City");


ps_rs_meta = prep_stmt -> getMetaData();
cout << "Schema Name: " << ps_rs_meta -> getSchemaName();

15
Parameter Meta Data

Example:

PreparedStatement *prep_stmt;
ParameterMetaData *param_meta;
string Qry ("INSERT INTO City (CityName) VALUES (?)");

prep_stmt = con -> prepareStatement (Qry);


param_meta = prep_stmt -> getParameterMetaData();
cout << "Number of parameters = "
<< param_meta -> getParameterCount();

16
Database Meta Data
Example:

Connection *dbcon;
DatabaseMetaData *dbcon_meta = dbcon -> getMetaData();

dbcon_meta = dbcon -> getMetaData();

cout << "Supports Transactions?: "


<< dbcon_meta -> supportsTransactions();

cout << "Maximum Connections: "


<< dbcon_meta -> getMaxConnections();

17
Transactions
Example:
Connection *con;
PreparedStatement *prep_stmt;
string Qry ("INSERT INTO City (CityName) VALUES (?)");

con -> setAutoCommit(0);


prep_stmt = con -> prepareStatement (Qry);

prep_stmt -> setString (1, "London, UK");


prep_stmt -> executeUpdate();
con -> rollback();

prep_stmt -> setString (1, "Paris, France");


prep_stmt -> executeUpdate();
con -> commit();

18
Fine-Grain Transaction Control : Savepoint(s)
Example:
Connection *con;
PreparedStatement *prep_stmt;
Savepoint *savept;
string Qry ("INSERT INTO City (CityName) VALUES (?)");

con -> setAutoCommit(0);


prep_stmt = con -> prepareStatement (Qry);

prep_stmt -> setString (1, "London, UK");


prep_stmt -> executeUpdate();

savept = con -> setSavepoint ("SAVEPT1");


prep_stmt -> setString (1, "Paris, France");
prep_stmt -> executeUpdate();
con -> rollback (savept);
con -> releaseSavepoint (savept);

con -> commit();


19
Stored Procedures
Example:

MySQL Client:

mysql> delimiter //
mysql> CREATE PROCEDURE addCity (IN cityname varchar(30))
-> BEGIN
-> INSERT INTO City VALUES (cityname);
-> END;
-> //
Query OK, 0 rows affected (0.00 sec)

Connector/C++ Client:

statement *stmt;
stmt -> execute ("CALL addCity('Tokyo, Japan')");

20
Exceptions, Warnings
Example:
Statement *stmt;

try {
..
throw SQLException ("Dummy Error ..");
..
SQLWarning *warn = stmt -> getWarnings();
if (warn != NULL) {
cout << "Warning: " << warn -> getMessage();
}
} catch (MethodNotImplementedException &e) { .. }
catch (InvalidArgumentException &e) { .. }
catch (SQLException &e) {
cout << "MySQL err: " << e.getErrorCode() << ", State: " << e.getSQLState()
<< "Error: " << e.what();
} catch (std::runtime_error &e) {.. }

21
Debug Traces using MySQL Client Library

Example:

Connection *con;
Statement *stmt;
ResultSet *rs;

con -> setClientOption("libmysql_debug", "d:t:O,/tmp/client.trc"); /* enable */


rs = stmt -> executeQuery ("SELECT * FROM City");
con -> setClientOption ("libmysql_debug", "f"); /* disable */

22
Sample Debug Trace
<cli_read_query_result
>mysql_real_query
| enter: handle: 0x808a228
| query: Query = 'SELECT * FROM City'
| >mysql_send_query
| | enter: rpl_parse: 0 rpl_pivot: 1
| <mysql_send_query
| >cli_advanced_command
| | >net_write_command
| | | enter: length: 37
| | <net_write_command
| | >net_flush
| | | <vio_is_blocking
| | | >net_real_write
| | | | >vio_write
| | | | | enter: sd: 4 buf: 0x808fa38 size: 42
...
Voluntary context switches 25, Involuntary context switches 5
>TERMINATE
| safe: sf_malloc_count: 4
| safe: Memory that was not free'ed (16420 bytes):
| safe: Maximum memory usage: 65569 bytes (65k) 23
Debug Traces using Driver's Tracing Module

Build Connector/C++ with Tracing Module Enabled:

cmake -DMYSQLCPPCONN_TRACE_ENABLE:BOOL=1 [..other options..]

Set the Environment Variable, and Run the Client Application:

# MYSQLCPPCONN_TRACE_ENABLED=1 ./connectorc++client

24
Miscellaneous Notes

25
Connector/C++ Roadmap

26

You might also like