SlideShare una empresa de Scribd logo
1 de 66
David Bennett
QA Engineer
April 15th
, 2015
Using MySQL with Java
Q2 2014
www.percona.com2
Who are you?

Java Experts, Intermediate, Beginners

MySQL Experts, Intermediate, Beginners

Developers, DBAs, System Admins

Just interested
www.percona.com3
Me

QA Engineer at Percona

Designer/Developer/Consultant

20+ years in technology

15+ years working with MySQL

15+ years working with Java

Focused on web apps

Linux devotee

I love MySQL, I like Java
Dave Bennett
www.percona.com4
Basic Topology
Java Application
(Web, Service, Desktop)
Java Runtime Engine
(JRE)
JDBC Interface
JDBC Driver (Connector/J)
MySQL
www.percona.com5
What is JDBC?

A standardized interface between Java and SQL

JDBC is to Java what ODBC is to Windows

Virtually all Java/SQL applications use JDBC

Like ODBC, JDBC is used more and more on
Servers, Desktop use waning.
www.percona.com6
What is Connector/J?

Most widely used JDBC Driver for MySQL today

Started life in 1998 as MM.MySQL (M. Matthews)

Acquired by MySQL AB in 2002

Owned by Oracle today, available under GPLv2

JDBC Type 4 – 100% Java – No Middleware
www.percona.com7
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com8
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com9
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com10
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com11
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com12
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com13
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com14
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com15
import java.sql.*;
public class MysqlVersion {
public static void main(String[] args)
throws SQLException,ClassNotFoundException {
Class.forName(
"com.mysql.jdbc.Driver"
);
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test","user","pwd"
);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT concat('Hello from mysql ',version()) AS msg"
);
if (rs.next()) {
System.out.println(rs.getString("msg"));
}
rs.close(); st.close(); con.close();
}
}
16 www.percona.com
www.percona.com17
Connector/J Basic* URL
jdbc:mysql://[host][:port]/[database][?prop=val[&prop=val]]
Where: is:
host TCP/IP host (defaults to IPV4 127.0.0.1)
port TCP/IP port (defaults to 3306)
database Database name (defaults to none)
prop A configuration property
val The configuration property's value
* There are more advanced options for other protocols (IPV6,
Named Pipes), replication, failover, load balancing, etc...
www.percona.com18
Connector/J URL Examples
jdbc:mysql://
Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver
Connect the MySQL server dbserver on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver:3307/mydb
Connect the MySQL server dbserver on port 3307 using database mydb.
jdbc:mysql://dbserver/mydb
Connect the MySQL server dbserver on port 3306 using database mydb.
www.percona.com19
Connector/J URL Examples
jdbc:mysql://
Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver
Connect the MySQL server dbserver on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver:3307/mydb
Connect the MySQL server dbserver on port 3307 using database mydb.
jdbc:mysql://dbserver/mydb
Connect the MySQL server dbserver on port 3306 using database mydb.
www.percona.com20
Connector/J URL Examples
jdbc:mysql://
Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver
Connect the MySQL server dbserver on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver:3307/mydb
Connect the MySQL server dbserver on port 3307 using database mydb.
jdbc:mysql://dbserver/mydb
Connect the MySQL server dbserver on port 3306 using database mydb.
www.percona.com21
Connector/J URL Examples
jdbc:mysql://
Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver
Connect the MySQL server dbserver on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver:3307/mydb
Connect the MySQL server dbserver on port 3307 using database mydb.
jdbc:mysql://dbserver/mydb
Connect the MySQL server dbserver on port 3306 using database mydb.
www.percona.com22
Connector/J URL Examples
jdbc:mysql://
Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver
Connect the MySQL server dbserver on port 3306 without specifying a
database. You must use Connection.setCatalog("{database}") or
database.table reference in queries.
jdbc:mysql://dbserver:3307/mydb
Connect the MySQL server dbserver on port 3307 using database mydb.
jdbc:mysql://dbserver/mydb
Connect the MySQL server dbserver on port 3306 using database mydb.
www.percona.com23
Connector/J parameters
Passing in JDBC URL:
dbProperties.load(MyClass.class.getClassLoader()
.getResourceAsStream("db.properties"));
Connection con =
DriverManager.getConnection("jdbc:mysql://", dbProperties);
Passing in a Properties file:
Connection con = DriverManager.getConnection(
"jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance"
);
MysqlDataSource mds=new MysqlDataSource();
mds.setUrl("jdbc:mysql://");
mds.setUser("user");
mds.setPassword("pwd");
mds.setAutoReconnect(true);
mds.setUseConfigs("maxPerformance");
Connection con=mds.getConnection();
Passing from MysqlDataSource set*() methods:
www.percona.com24
Connector/J parameters
Passing in JDBC URL:
dbProperties.load(MyClass.class.getClassLoader()
.getResourceAsStream("db.properties"));
Connection con =
DriverManager.getConnection("jdbc:mysql://", dbProperties);
Passing in a Properties file:
Connection con = DriverManager.getConnection(
"jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance"
);
MysqlDataSource mds=new MysqlDataSource();
mds.setUrl("jdbc:mysql://");
mds.setUser("user");
mds.setPassword("pwd");
mds.setAutoReconnect(true);
mds.setUseConfigs("maxPerformance");
Connection con=mds.getConnection();
Passing from MysqlDataSource set*() methods:
www.percona.com25
Connector/J parameters
Passing in JDBC URL:
dbProperties.load(MyClass.class.getClassLoader()
.getResourceAsStream("db.properties"));
Connection con =
DriverManager.getConnection("jdbc:mysql://", dbProperties);
Passing in a Properties file:
Connection con = DriverManager.getConnection(
"jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance"
);
MysqlDataSource mds=new MysqlDataSource();
mds.setUrl("jdbc:mysql://");
mds.setUser("user");
mds.setPassword("pwd");
mds.setAutoReconnect(true);
mds.setUseConfigs("maxPerformance");
Connection con=mds.getConnection();
Passing from MysqlDataSource set*() methods:
www.percona.com26
Connector/J parameters
Passing in JDBC URL:
dbProperties.load(MyClass.class.getClassLoader()
.getResourceAsStream("db.properties"));
Connection con =
DriverManager.getConnection("jdbc:mysql://", dbProperties);
Passing in a Properties file:
Connection con = DriverManager.getConnection(
"jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance"
);
MysqlDataSource mds=new MysqlDataSource();
mds.setUrl("jdbc:mysql://");
mds.setUser("user");
mds.setPassword("pwd");
mds.setAutoReconnect(true);
mds.setUseConfigs("maxPerformance");
Connection con=mds.getConnection();
Passing from MysqlDataSource set*() methods:
www.percona.com27
Generic JDBC App Example
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class DBHello {
public static void main(String[] args)
throws SQLException,ClassNotFoundException,IOException {
Properties dbp = new Properties();
dbp.load(DBHello.class.getClassLoader()
.getResourceAsStream("db.properties"));
Class.forName(dbp.getProperty("class"));
Connection con =
DriverManager.getConnection(dbp.getProperty("url"), dbp);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(dbp.getProperty("versionQuery"));
if (rs.next()) {
System.out.printf("Hello from %sn",rs.getString("version"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com28
Generic JDBC App Example
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class DBHello {
public static void main(String[] args)
throws SQLException,ClassNotFoundException,IOException {
Properties dbp = new Properties();
dbp.load(DBHello.class.getClassLoader()
.getResourceAsStream("db.properties"));
Class.forName(dbp.getProperty("class"));
Connection con =
DriverManager.getConnection(dbp.getProperty("url"), dbp);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(dbp.getProperty("versionQuery"));
if (rs.next()) {
System.out.printf("Hello from %sn",rs.getString("version"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com29
Generic JDBC App Example
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class DBHello {
public static void main(String[] args)
throws SQLException,ClassNotFoundException,IOException {
Properties dbp = new Properties();
dbp.load(DBHello.class.getClassLoader()
.getResourceAsStream("db.properties"));
Class.forName(dbp.getProperty("class"));
Connection con =
DriverManager.getConnection(dbp.getProperty("url"), dbp);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(dbp.getProperty("versionQuery"));
if (rs.next()) {
System.out.printf("Hello from %sn",rs.getString("version"));
}
rs.close(); st.close(); con.close();
}
}
www.percona.com30
Generic JDBC App Example
db.properties configured for MySQL:
# driver
class=com.mysql.jdbc.Driver
# connection url
url=jdbc:mysql://localhost
user=user
password=pwd
# parameters
autoReconnect=true
useConfigs=maxPerformance
# version query
versionQuery=SELECT CONCAT_WS(' ',@@version_comment,@@version,
@@version_compile_os,@@version_compile_machine) AS `version`
Returns:
Hello from MySQL Community Server (GPL) 5.6.23-log Linux x86_64
www.percona.com31
Prepared Statements

Security – Better protection from SQL injection attacks,
parameters are sent separately, escaping unnecessary

Performance – Prepared Statements are re-usable.
Interpretation and Optimization happens only once.

More Performance – Combined with Pooling/Caching.

Use them whenever you can.
www.percona.com32
Let's do something useful

Runs as a service, records storage capacity to a table

Runs as a report, outputs capacity growth over time

Load JDBC configuration from a Java properties file

PreparedStatement Query with ResultSet

Use and Reuse of PreparedStatement

Batch inserts using addBatch/executeBatch

Dynamic DDL creation
DiskFreeChecker.java
github.com/dbpercona/DiskFreeChecker
www.percona.com33
Prepared Statement Query
pst=con.prepareStatement(
"SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?");
pst.setString(1, hostname);
pst.setTimestamp(2, ts);
rs=pst.executeQuery();
while (rs.next()) {
DiskFreeEntry dfe=new DiskFreeEntry();
dfe.id = rs.getLong("id");
dfe.hostname = rs.getString("hostname");
dfe.fileSystemName = rs.getString("file_system_name");
dfe.totalSpace = rs.getLong("total_space");
dfe.spaceUsed = rs.getLong("space_used");
dfe.spaceFree = rs.getLong("space_free");
dfe.percentageUsed = rs.getBigDecimal("percentage_used");
dfe.fileSystemRoot = rs.getString("file_system_root");
dfe.when = rs.getTimestamp("file_system_root");
diskFreeEntries.put(dfe.fileSystemRoot,dfe);
}
rs.close(); pst.close();
www.percona.com34
Prepared Statement Query
pst=con.prepareStatement(
"SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?");
pst.setString(1, hostname);
pst.setTimestamp(2, ts);
rs=pst.executeQuery();
while (rs.next()) {
DiskFreeEntry dfe=new DiskFreeEntry();
dfe.id = rs.getLong("id");
dfe.hostname = rs.getString("hostname");
dfe.fileSystemName = rs.getString("file_system_name");
dfe.totalSpace = rs.getLong("total_space");
dfe.spaceUsed = rs.getLong("space_used");
dfe.spaceFree = rs.getLong("space_free");
dfe.percentageUsed = rs.getBigDecimal("percentage_used");
dfe.fileSystemRoot = rs.getString("file_system_root");
dfe.when = rs.getTimestamp("file_system_root");
diskFreeEntries.put(dfe.fileSystemRoot,dfe);
}
rs.close(); pst.close();
www.percona.com35
Prepared Statement Query
pst=con.prepareStatement(
"SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?");
pst.setString(1, hostname);
pst.setTimestamp(2, ts);
rs=pst.executeQuery();
while (rs.next()) {
DiskFreeEntry dfe=new DiskFreeEntry();
dfe.id = rs.getLong("id");
dfe.hostname = rs.getString("hostname");
dfe.fileSystemName = rs.getString("file_system_name");
dfe.totalSpace = rs.getLong("total_space");
dfe.spaceUsed = rs.getLong("space_used");
dfe.spaceFree = rs.getLong("space_free");
dfe.percentageUsed = rs.getBigDecimal("percentage_used");
dfe.fileSystemRoot = rs.getString("file_system_root");
dfe.when = rs.getTimestamp("file_system_root");
diskFreeEntries.put(dfe.fileSystemRoot,dfe);
}
rs.close(); pst.close();
www.percona.com36
Prepared Statement Query
pst=con.prepareStatement(
"SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?");
pst.setString(1, hostname);
pst.setTimestamp(2, ts);
rs=pst.executeQuery();
while (rs.next()) {
DiskFreeEntry dfe=new DiskFreeEntry();
dfe.id = rs.getLong("id");
dfe.hostname = rs.getString("hostname");
dfe.fileSystemName = rs.getString("file_system_name");
dfe.totalSpace = rs.getLong("total_space");
dfe.spaceUsed = rs.getLong("space_used");
dfe.spaceFree = rs.getLong("space_free");
dfe.percentageUsed = rs.getBigDecimal("percentage_used");
dfe.fileSystemRoot = rs.getString("file_system_root");
dfe.when = rs.getTimestamp("file_system_root");
diskFreeEntries.put(dfe.fileSystemRoot,dfe);
}
rs.close(); pst.close();
www.percona.com37
Prepared Statement Query
pst=con.prepareStatement(
"SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?");
pst.setString(1, hostname);
pst.setTimestamp(2, ts);
rs=pst.executeQuery();
while (rs.next()) {
DiskFreeEntry dfe=new DiskFreeEntry();
dfe.id = rs.getLong("id");
dfe.hostname = rs.getString("hostname");
dfe.fileSystemName = rs.getString("file_system_name");
dfe.totalSpace = rs.getLong("total_space");
dfe.spaceUsed = rs.getLong("space_used");
dfe.spaceFree = rs.getLong("space_free");
dfe.percentageUsed = rs.getBigDecimal("percentage_used");
dfe.fileSystemRoot = rs.getString("file_system_root");
dfe.when = rs.getTimestamp("file_system_root");
diskFreeEntries.put(dfe.fileSystemRoot,dfe);
}
rs.close(); pst.close();
www.percona.com38
Prepared Statement Query
pst=con.prepareStatement(
"SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?");
pst.setString(1, hostname);
pst.setTimestamp(2, ts);
rs=pst.executeQuery();
while (rs.next()) {
DiskFreeEntry dfe=new DiskFreeEntry();
dfe.id = rs.getLong("id");
dfe.hostname = rs.getString("hostname");
dfe.fileSystemName = rs.getString("file_system_name");
dfe.totalSpace = rs.getLong("total_space");
dfe.spaceUsed = rs.getLong("space_used");
dfe.spaceFree = rs.getLong("space_free");
dfe.percentageUsed = rs.getBigDecimal("percentage_used");
dfe.fileSystemRoot = rs.getString("file_system_root");
dfe.when = rs.getTimestamp("file_system_root");
diskFreeEntries.put(dfe.fileSystemRoot,dfe);
}
rs.close(); pst.close();
www.percona.com39
Prepared Statement Query
pst=con.prepareStatement(
"SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?");
pst.setString(1, hostname);
pst.setTimestamp(2, ts);
rs=pst.executeQuery();
while (rs.next()) {
DiskFreeEntry dfe=new DiskFreeEntry();
dfe.id = rs.getLong("id");
dfe.hostname = rs.getString("hostname");
dfe.fileSystemName = rs.getString("file_system_name");
dfe.totalSpace = rs.getLong("total_space");
dfe.spaceUsed = rs.getLong("space_used");
dfe.spaceFree = rs.getLong("space_free");
dfe.percentageUsed = rs.getBigDecimal("percentage_used");
dfe.fileSystemRoot = rs.getString("file_system_root");
dfe.when = rs.getTimestamp("file_system_root");
diskFreeEntries.put(dfe.fileSystemRoot,dfe);
}
rs.close(); pst.close();
www.percona.com40
Prepared Statement Reuse
pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree "
+ "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) "
+ "AND `hostname` = ?");
// then
pst.setBigDecimal(1, secondsBack);
pst.setString(2, hostname);
rs = pst.executeQuery();
if (rs.next()) {
then = rs.getTimestamp(1);
}
rs.close();
// now
pst.setInt(1, 0);
rs = pst.executeQuery();
if (rs.next()) {
now = rs.getTimestamp(1);
}
rs.close();
pst.close();
www.percona.com41
Prepared Statement Reuse
pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree "
+ "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) "
+ "AND `hostname` = ?");
// then
pst.setBigDecimal(1, secondsBack);
pst.setString(2, hostname);
rs = pst.executeQuery();
if (rs.next()) {
then = rs.getTimestamp(1);
}
rs.close();
// now
pst.setInt(1, 0);
rs = pst.executeQuery();
if (rs.next()) {
now = rs.getTimestamp(1);
}
rs.close();
pst.close();
www.percona.com42
Prepared Statement Reuse
pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree "
+ "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) "
+ "AND `hostname` = ?");
// then
pst.setBigDecimal(1, secondsBack);
pst.setString(2, hostname);
rs = pst.executeQuery();
if (rs.next()) {
then = rs.getTimestamp(1);
}
rs.close();
// now
pst.setInt(1, 0);
rs = pst.executeQuery();
if (rs.next()) {
now = rs.getTimestamp(1);
}
rs.close();
pst.close();
www.percona.com43
Prepared Statement Reuse
pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree "
+ "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) "
+ "AND `hostname` = ?");
// then
pst.setBigDecimal(1, secondsBack);
pst.setString(2, hostname);
rs = pst.executeQuery();
if (rs.next()) {
then = rs.getTimestamp(1);
}
rs.close();
// now
pst.setInt(1, 0);
rs = pst.executeQuery();
if (rs.next()) {
now = rs.getTimestamp(1);
}
rs.close();
pst.close();
www.percona.com44
Prepared Statement Reuse
pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree "
+ "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) "
+ "AND `hostname` = ?");
// then
pst.setBigDecimal(1, secondsBack);
pst.setString(2, hostname);
rs = pst.executeQuery();
if (rs.next()) {
then = rs.getTimestamp(1);
}
rs.close();
// now
pst.setInt(1, 0);
rs = pst.executeQuery();
if (rs.next()) {
now = rs.getTimestamp(1);
}
rs.close();
pst.close();
www.percona.com45
Prepared Statement Reuse
pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree "
+ "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) "
+ "AND `hostname` = ?");
// then
pst.setBigDecimal(1, secondsBack);
pst.setString(2, hostname);
rs = pst.executeQuery();
if (rs.next()) {
then = rs.getTimestamp(1);
}
rs.close();
// now
pst.setInt(1, 0);
rs = pst.executeQuery();
if (rs.next()) {
now = rs.getTimestamp(1);
}
rs.close();
pst.close();
www.percona.com46
Prepared Statement Batches
pst=con.prepareStatement( // prepare insert
"INSERT INTO diskfree (`hostname`,`file_system_name`,"+
"`total_space`,`space_used`,`space_free`,`percentage_used`,"+
"`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)");
for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) {
pst.setString ( 1, diskFreeEntry.hostname );
pst.setString ( 2, diskFreeEntry.fileSystemName );
pst.setLong ( 3, diskFreeEntry.totalSpace );
pst.setLong ( 4, diskFreeEntry.spaceUsed );
pst.setLong ( 5, diskFreeEntry.spaceFree );
pst.setBigDecimal( 6, diskFreeEntry.percentageUsed );
pst.setString ( 7, diskFreeEntry.fileSystemRoot );
pst.setTimestamp ( 8, when );
pst.addBatch(); // add to batch
}
int[] inserts=pst.executeBatch(); // execute batch
int totalInserts=0;
for (int i : inserts) totalInserts += i; // compute total
www.percona.com47
Prepared Statement Batches
pst=con.prepareStatement( // prepare insert
"INSERT INTO diskfree (`hostname`,`file_system_name`,"+
"`total_space`,`space_used`,`space_free`,`percentage_used`,"+
"`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)");
for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) {
pst.setString ( 1, diskFreeEntry.hostname );
pst.setString ( 2, diskFreeEntry.fileSystemName );
pst.setLong ( 3, diskFreeEntry.totalSpace );
pst.setLong ( 4, diskFreeEntry.spaceUsed );
pst.setLong ( 5, diskFreeEntry.spaceFree );
pst.setBigDecimal( 6, diskFreeEntry.percentageUsed );
pst.setString ( 7, diskFreeEntry.fileSystemRoot );
pst.setTimestamp ( 8, when );
pst.addBatch(); // add to batch
}
int[] inserts=pst.executeBatch(); // execute batch
int totalInserts=0;
for (int i : inserts) totalInserts += i; // compute total
www.percona.com48
Prepared Statement Batches
pst=con.prepareStatement( // prepare insert
"INSERT INTO diskfree (`hostname`,`file_system_name`,"+
"`total_space`,`space_used`,`space_free`,`percentage_used`,"+
"`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)");
for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) {
pst.setString ( 1, diskFreeEntry.hostname );
pst.setString ( 2, diskFreeEntry.fileSystemName );
pst.setLong ( 3, diskFreeEntry.totalSpace );
pst.setLong ( 4, diskFreeEntry.spaceUsed );
pst.setLong ( 5, diskFreeEntry.spaceFree );
pst.setBigDecimal( 6, diskFreeEntry.percentageUsed );
pst.setString ( 7, diskFreeEntry.fileSystemRoot );
pst.setTimestamp ( 8, when );
pst.addBatch(); // add to batch
}
int[] inserts=pst.executeBatch(); // execute batch
int totalInserts=0;
for (int i : inserts) totalInserts += i; // compute total
www.percona.com49
Prepared Statement Batches
pst=con.prepareStatement( // prepare insert
"INSERT INTO diskfree (`hostname`,`file_system_name`,"+
"`total_space`,`space_used`,`space_free`,`percentage_used`,"+
"`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)");
for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) {
pst.setString ( 1, diskFreeEntry.hostname );
pst.setString ( 2, diskFreeEntry.fileSystemName );
pst.setLong ( 3, diskFreeEntry.totalSpace );
pst.setLong ( 4, diskFreeEntry.spaceUsed );
pst.setLong ( 5, diskFreeEntry.spaceFree );
pst.setBigDecimal( 6, diskFreeEntry.percentageUsed );
pst.setString ( 7, diskFreeEntry.fileSystemRoot );
pst.setTimestamp ( 8, when );
pst.addBatch(); // add to batch
}
int[] inserts=pst.executeBatch(); // execute batch
int totalInserts=0;
for (int i : inserts) totalInserts += i; // compute total
www.percona.com50
Prepared Statement Batches
pst=con.prepareStatement( // prepare insert
"INSERT INTO diskfree (`hostname`,`file_system_name`,"+
"`total_space`,`space_used`,`space_free`,`percentage_used`,"+
"`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)");
for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) {
pst.setString ( 1, diskFreeEntry.hostname );
pst.setString ( 2, diskFreeEntry.fileSystemName );
pst.setLong ( 3, diskFreeEntry.totalSpace );
pst.setLong ( 4, diskFreeEntry.spaceUsed );
pst.setLong ( 5, diskFreeEntry.spaceFree );
pst.setBigDecimal( 6, diskFreeEntry.percentageUsed );
pst.setString ( 7, diskFreeEntry.fileSystemRoot );
pst.setTimestamp ( 8, when );
pst.addBatch(); // add to batch
}
int[] inserts=pst.executeBatch(); // execute batch
int totalInserts=0;
for (int i : inserts) totalInserts += i; // compute total
www.percona.com51
Prepared Statement Batches
pst=con.prepareStatement( // prepare insert
"INSERT INTO diskfree (`hostname`,`file_system_name`,"+
"`total_space`,`space_used`,`space_free`,`percentage_used`,"+
"`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)");
for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) {
pst.setString ( 1, diskFreeEntry.hostname );
pst.setString ( 2, diskFreeEntry.fileSystemName );
pst.setLong ( 3, diskFreeEntry.totalSpace );
pst.setLong ( 4, diskFreeEntry.spaceUsed );
pst.setLong ( 5, diskFreeEntry.spaceFree );
pst.setBigDecimal( 6, diskFreeEntry.percentageUsed );
pst.setString ( 7, diskFreeEntry.fileSystemRoot );
pst.setTimestamp ( 8, when );
pst.addBatch(); // add to batch
}
int[] inserts=pst.executeBatch(); // execute batch
int totalInserts=0;
for (int i : inserts) totalInserts += i; // compute total
www.percona.com52
Prepared Statement Batches
pst=con.prepareStatement( // prepare insert
"INSERT INTO diskfree (`hostname`,`file_system_name`,"+
"`total_space`,`space_used`,`space_free`,`percentage_used`,"+
"`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)");
for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) {
pst.setString ( 1, diskFreeEntry.hostname );
pst.setString ( 2, diskFreeEntry.fileSystemName );
pst.setLong ( 3, diskFreeEntry.totalSpace );
pst.setLong ( 4, diskFreeEntry.spaceUsed );
pst.setLong ( 5, diskFreeEntry.spaceFree );
pst.setBigDecimal( 6, diskFreeEntry.percentageUsed );
pst.setString ( 7, diskFreeEntry.fileSystemRoot );
pst.setTimestamp ( 8, when );
pst.addBatch(); // add to batch
}
int[] inserts=pst.executeBatch(); // execute batch
int totalInserts=0;
for (int i : inserts) totalInserts += i; // compute total
www.percona.com53
Prepared Statement Writes
int keepDays=30;
String strKeepDays=dbp.getProperty("keep.days");
if (strKeepDays != null)
keepDays = new Integer(strKeepDays).intValue();
pst = con.prepareStatement(
"DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)");
pst.setInt(1, keepDays);
pst.execute();
int updateCount=pst.getUpdateCount();
if (updateCount > 0)
System.out.println("Cleaned up "+updateCount+" old entries.");
else
System.out.println("No old entries to clean up.");
pst.close();
www.percona.com54
int keepDays=30;
String strKeepDays=dbp.getProperty("keep.days");
if (strKeepDays != null)
keepDays = new Integer(strKeepDays).intValue();
pst = con.prepareStatement(
"DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)");
pst.setInt(1, keepDays);
pst.execute();
int updateCount=pst.getUpdateCount();
if (updateCount > 0)
System.out.println("Cleaned up "+updateCount+" old entries.");
else
System.out.println("No old entries to clean up.");
pst.close();
Prepared Statement Writes
www.percona.com55
Prepared Statement Writes
int keepDays=30;
String strKeepDays=dbp.getProperty("keep.days");
if (strKeepDays != null)
keepDays = new Integer(strKeepDays).intValue();
pst = con.prepareStatement(
"DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)");
pst.setInt(1, keepDays);
pst.execute();
int updateCount=pst.getUpdateCount();
if (updateCount > 0)
System.out.println("Cleaned up "+updateCount+" old entries.");
else
System.out.println("No old entries to clean up.");
pst.close();
www.percona.com56
Prepared Statement Writes
int keepDays=30;
String strKeepDays=dbp.getProperty("keep.days");
if (strKeepDays != null)
keepDays = new Integer(strKeepDays).intValue();
pst = con.prepareStatement(
"DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)");
pst.setInt(1, keepDays);
pst.execute();
int updateCount=pst.getUpdateCount();
if (updateCount > 0)
System.out.println("Cleaned up "+updateCount+" old entries.");
else
System.out.println("No old entries to clean up.");
pst.close();
www.percona.com57
Prepared Statement Writes
int keepDays=30;
String strKeepDays=dbp.getProperty("keep.days");
if (strKeepDays != null)
keepDays = new Integer(strKeepDays).intValue();
pst = con.prepareStatement(
"DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)");
pst.setInt(1, keepDays);
pst.execute();
int updateCount=pst.getUpdateCount();
if (updateCount > 0)
System.out.println("Cleaned up "+updateCount+" old entries.");
else
System.out.println("No old entries to clean up.");
pst.close();
www.percona.com58
Performance parameters
Parameter What it does
cachePrepStmts=true If true, cache prepared statements on client side
cacheCallableStmts=true If true, cache prepared stored procedure calls
CacheServerConfiguration=
true
If true, reduces connect queries by caching
server configuration variables.
useLocalSessionState=true If true, reduces setup queries by using the local
session state
elideSetAutoCommits=true If true, only set autocommit if the server doesn't
match the client autocommit setting.
AlwaysSendSetIsolation=
false
If false, doesn't set the transaction isolation level
on connect. Uses server default isolation level
enableQueryTimeouts=false If false, disables query timeouts
www.percona.com59
Performance parameters
Parameter What it does
cachePrepStmts=true If true, cache prepared statements on client side
cacheCallableStmts=true If true, cache prepared stored procedure calls
CacheServerConfiguration=
true
If true, reduces connect queries by caching
server configuration variables.
useLocalSessionState=true If true, reduces setup queries by using the local
session state
elideSetAutoCommits=true If true, only set autocommit if the server doesn't
match the client autocommit setting.
AlwaysSendSetIsolation=
false
If false, doesn't set the transaction isolation level
on connect. Uses server default isolation level
enableQueryTimeouts=false If false, disables query timeouts
useConfigs=maxPerformance
www.percona.com60
Debugging parameters
Parameter What it does
profileSQL=true If true, log query execution times to the
configured logger.
gatherPerfMetrics=true If true, collect performance metrics to the
configured logger.
useUsageAdvisor=true If true, inefficient use of JDBC and MySQL will
logged to the configured logger as warnings.
logSlowQueries=true If true, 'slow' queries will be logged to the
configured logger (slowQueryThresholdMillis)
explainSlowQueries=true If true, an 'EXPLAIN' statement for slow queries
will be logged to the configured logger.
www.percona.com61
Debugging parameters
Parameter What it does
profileSQL=true If true, log query execution times to the
configured logger.
gatherPerfMetrics=true If true, collect performance metrics to the
configured logger.
useUsageAdvisor=true If true, inefficient use of JDBC and MySQL will
logged to the configured logger as warnings.
logSlowQueries=true If true, 'slow' queries will be logged to the
configured logger (slowQueryThresholdMillis)
explainSlowQueries=true If true, an 'EXPLAIN' statement for slow queries
will be logged to the configured logger.
useConfigs=fullDebug
www.percona.com62
Other Handy Parameters

autoReconnect

characterEncoding

useInformationSchema

maxRows
www.percona.com63
Alternative JDBC Driver

MariaDB Java Client

Maintained-ed by MariaDB team

Fork from Drizzle JDBC

Stable release 1.1.8

Compatible with:

MySQL

Percona Server / PXC

MariaDB
www.percona.com64
Alternative JDBC Driver

Pros

Maybe be faster in some cases

It is under active development

Cons

Not as feature rich

Not as mature
www.percona.com65
What to learn about next

Connection Pooling

DBCP, C3P0, BoneCP

JNDI / Container Managed

DataSource, Spring

Object Relational Mapping

JPA, Hibernate, Spring
www.percona.com66 www.percona.com
THANK YOU

Más contenido relacionado

La actualidad más candente

JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in muleAnilKumar Etagowni
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)Fad Zulkifli
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutesglassfish
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Integrate with database by groovy
Integrate with database by groovyIntegrate with database by groovy
Integrate with database by groovySon Nguyen
 
Resthub framework presentation
Resthub framework presentationResthub framework presentation
Resthub framework presentationSébastien Deleuze
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)DK Lee
 
MySQL 8.0.16 New Features Summary
MySQL 8.0.16 New Features SummaryMySQL 8.0.16 New Features Summary
MySQL 8.0.16 New Features SummaryOlivier DASINI
 

La actualidad más candente (20)

JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in mule
 
jsp MySQL database connectivity
jsp MySQL database connectivityjsp MySQL database connectivity
jsp MySQL database connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc
JdbcJdbc
Jdbc
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
Select query in JDBC
Select query in JDBCSelect query in JDBC
Select query in JDBC
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Integrate with database by groovy
Integrate with database by groovyIntegrate with database by groovy
Integrate with database by groovy
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Resthub framework presentation
Resthub framework presentationResthub framework presentation
Resthub framework presentation
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
MySQL 8.0.16 New Features Summary
MySQL 8.0.16 New Features SummaryMySQL 8.0.16 New Features Summary
MySQL 8.0.16 New Features Summary
 

Destacado

Destacado (20)

Aa service bulletinfeedingthemodernbreederaug2014-en
Aa service bulletinfeedingthemodernbreederaug2014-enAa service bulletinfeedingthemodernbreederaug2014-en
Aa service bulletinfeedingthemodernbreederaug2014-en
 
Traballo
TraballoTraballo
Traballo
 
مهارات الابيوس
مهارات الابيوسمهارات الابيوس
مهارات الابيوس
 
G321 Evaluation Question 5
G321 Evaluation Question 5G321 Evaluation Question 5
G321 Evaluation Question 5
 
Taller 11
Taller 11Taller 11
Taller 11
 
Inteligencia artificial
Inteligencia artificial Inteligencia artificial
Inteligencia artificial
 
Integrasi Data Lokasi Kebencanaan dengan Menggunakan WebGIS berbasis Google M...
Integrasi Data Lokasi Kebencanaan dengan Menggunakan WebGIS berbasis Google M...Integrasi Data Lokasi Kebencanaan dengan Menggunakan WebGIS berbasis Google M...
Integrasi Data Lokasi Kebencanaan dengan Menggunakan WebGIS berbasis Google M...
 
2º Reinado no Brasil
2º Reinado no Brasil2º Reinado no Brasil
2º Reinado no Brasil
 
Epidemic Curve
Epidemic CurveEpidemic Curve
Epidemic Curve
 
La empresa familiar en méxico
La empresa familiar en méxicoLa empresa familiar en méxico
La empresa familiar en méxico
 
Evolución del televisor
Evolución del televisorEvolución del televisor
Evolución del televisor
 
Proyecto de internalización
Proyecto de internalización Proyecto de internalización
Proyecto de internalización
 
Politica de dividendos
Politica de dividendosPolitica de dividendos
Politica de dividendos
 
101 perguntas
101   perguntas101   perguntas
101 perguntas
 
Personajes.
Personajes.Personajes.
Personajes.
 
Stress is major factor for hair loss
Stress is major factor for hair lossStress is major factor for hair loss
Stress is major factor for hair loss
 
Folleto
FolletoFolleto
Folleto
 
Ana
AnaAna
Ana
 
40 Years Since Cambodian Genocide
40 Years Since Cambodian Genocide40 Years Since Cambodian Genocide
40 Years Since Cambodian Genocide
 
RESUME
RESUMERESUME
RESUME
 

Similar a Plmce2015 java 101 - david bennett

Similar a Plmce2015 java 101 - david bennett (20)

Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
JDBC
JDBCJDBC
JDBC
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Jdbc
JdbcJdbc
Jdbc
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc
Jdbc   Jdbc
Jdbc
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Lecture17
Lecture17Lecture17
Lecture17
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 

Último

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

Plmce2015 java 101 - david bennett

  • 1. David Bennett QA Engineer April 15th , 2015 Using MySQL with Java Q2 2014
  • 2. www.percona.com2 Who are you?  Java Experts, Intermediate, Beginners  MySQL Experts, Intermediate, Beginners  Developers, DBAs, System Admins  Just interested
  • 3. www.percona.com3 Me  QA Engineer at Percona  Designer/Developer/Consultant  20+ years in technology  15+ years working with MySQL  15+ years working with Java  Focused on web apps  Linux devotee  I love MySQL, I like Java Dave Bennett
  • 4. www.percona.com4 Basic Topology Java Application (Web, Service, Desktop) Java Runtime Engine (JRE) JDBC Interface JDBC Driver (Connector/J) MySQL
  • 5. www.percona.com5 What is JDBC?  A standardized interface between Java and SQL  JDBC is to Java what ODBC is to Windows  Virtually all Java/SQL applications use JDBC  Like ODBC, JDBC is used more and more on Servers, Desktop use waning.
  • 6. www.percona.com6 What is Connector/J?  Most widely used JDBC Driver for MySQL today  Started life in 1998 as MM.MySQL (M. Matthews)  Acquired by MySQL AB in 2002  Owned by Oracle today, available under GPLv2  JDBC Type 4 – 100% Java – No Middleware
  • 7. www.percona.com7 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 8. www.percona.com8 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 9. www.percona.com9 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 10. www.percona.com10 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 11. www.percona.com11 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 12. www.percona.com12 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 13. www.percona.com13 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 14. www.percona.com14 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 15. www.percona.com15 import java.sql.*; public class MysqlVersion { public static void main(String[] args) throws SQLException,ClassNotFoundException { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test","user","pwd" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT concat('Hello from mysql ',version()) AS msg" ); if (rs.next()) { System.out.println(rs.getString("msg")); } rs.close(); st.close(); con.close(); } }
  • 17. www.percona.com17 Connector/J Basic* URL jdbc:mysql://[host][:port]/[database][?prop=val[&prop=val]] Where: is: host TCP/IP host (defaults to IPV4 127.0.0.1) port TCP/IP port (defaults to 3306) database Database name (defaults to none) prop A configuration property val The configuration property's value * There are more advanced options for other protocols (IPV6, Named Pipes), replication, failover, load balancing, etc...
  • 18. www.percona.com18 Connector/J URL Examples jdbc:mysql:// Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver Connect the MySQL server dbserver on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver:3307/mydb Connect the MySQL server dbserver on port 3307 using database mydb. jdbc:mysql://dbserver/mydb Connect the MySQL server dbserver on port 3306 using database mydb.
  • 19. www.percona.com19 Connector/J URL Examples jdbc:mysql:// Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver Connect the MySQL server dbserver on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver:3307/mydb Connect the MySQL server dbserver on port 3307 using database mydb. jdbc:mysql://dbserver/mydb Connect the MySQL server dbserver on port 3306 using database mydb.
  • 20. www.percona.com20 Connector/J URL Examples jdbc:mysql:// Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver Connect the MySQL server dbserver on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver:3307/mydb Connect the MySQL server dbserver on port 3307 using database mydb. jdbc:mysql://dbserver/mydb Connect the MySQL server dbserver on port 3306 using database mydb.
  • 21. www.percona.com21 Connector/J URL Examples jdbc:mysql:// Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver Connect the MySQL server dbserver on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver:3307/mydb Connect the MySQL server dbserver on port 3307 using database mydb. jdbc:mysql://dbserver/mydb Connect the MySQL server dbserver on port 3306 using database mydb.
  • 22. www.percona.com22 Connector/J URL Examples jdbc:mysql:// Connect the MySQL server at 127.0.0.1 on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver Connect the MySQL server dbserver on port 3306 without specifying a database. You must use Connection.setCatalog("{database}") or database.table reference in queries. jdbc:mysql://dbserver:3307/mydb Connect the MySQL server dbserver on port 3307 using database mydb. jdbc:mysql://dbserver/mydb Connect the MySQL server dbserver on port 3306 using database mydb.
  • 23. www.percona.com23 Connector/J parameters Passing in JDBC URL: dbProperties.load(MyClass.class.getClassLoader() .getResourceAsStream("db.properties")); Connection con = DriverManager.getConnection("jdbc:mysql://", dbProperties); Passing in a Properties file: Connection con = DriverManager.getConnection( "jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance" ); MysqlDataSource mds=new MysqlDataSource(); mds.setUrl("jdbc:mysql://"); mds.setUser("user"); mds.setPassword("pwd"); mds.setAutoReconnect(true); mds.setUseConfigs("maxPerformance"); Connection con=mds.getConnection(); Passing from MysqlDataSource set*() methods:
  • 24. www.percona.com24 Connector/J parameters Passing in JDBC URL: dbProperties.load(MyClass.class.getClassLoader() .getResourceAsStream("db.properties")); Connection con = DriverManager.getConnection("jdbc:mysql://", dbProperties); Passing in a Properties file: Connection con = DriverManager.getConnection( "jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance" ); MysqlDataSource mds=new MysqlDataSource(); mds.setUrl("jdbc:mysql://"); mds.setUser("user"); mds.setPassword("pwd"); mds.setAutoReconnect(true); mds.setUseConfigs("maxPerformance"); Connection con=mds.getConnection(); Passing from MysqlDataSource set*() methods:
  • 25. www.percona.com25 Connector/J parameters Passing in JDBC URL: dbProperties.load(MyClass.class.getClassLoader() .getResourceAsStream("db.properties")); Connection con = DriverManager.getConnection("jdbc:mysql://", dbProperties); Passing in a Properties file: Connection con = DriverManager.getConnection( "jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance" ); MysqlDataSource mds=new MysqlDataSource(); mds.setUrl("jdbc:mysql://"); mds.setUser("user"); mds.setPassword("pwd"); mds.setAutoReconnect(true); mds.setUseConfigs("maxPerformance"); Connection con=mds.getConnection(); Passing from MysqlDataSource set*() methods:
  • 26. www.percona.com26 Connector/J parameters Passing in JDBC URL: dbProperties.load(MyClass.class.getClassLoader() .getResourceAsStream("db.properties")); Connection con = DriverManager.getConnection("jdbc:mysql://", dbProperties); Passing in a Properties file: Connection con = DriverManager.getConnection( "jdbc:mysql://host/db?autoReconnect=true&useConfigs=maxPerformance" ); MysqlDataSource mds=new MysqlDataSource(); mds.setUrl("jdbc:mysql://"); mds.setUser("user"); mds.setPassword("pwd"); mds.setAutoReconnect(true); mds.setUseConfigs("maxPerformance"); Connection con=mds.getConnection(); Passing from MysqlDataSource set*() methods:
  • 27. www.percona.com27 Generic JDBC App Example import java.io.IOException; import java.sql.*; import java.util.Properties; public class DBHello { public static void main(String[] args) throws SQLException,ClassNotFoundException,IOException { Properties dbp = new Properties(); dbp.load(DBHello.class.getClassLoader() .getResourceAsStream("db.properties")); Class.forName(dbp.getProperty("class")); Connection con = DriverManager.getConnection(dbp.getProperty("url"), dbp); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(dbp.getProperty("versionQuery")); if (rs.next()) { System.out.printf("Hello from %sn",rs.getString("version")); } rs.close(); st.close(); con.close(); } }
  • 28. www.percona.com28 Generic JDBC App Example import java.io.IOException; import java.sql.*; import java.util.Properties; public class DBHello { public static void main(String[] args) throws SQLException,ClassNotFoundException,IOException { Properties dbp = new Properties(); dbp.load(DBHello.class.getClassLoader() .getResourceAsStream("db.properties")); Class.forName(dbp.getProperty("class")); Connection con = DriverManager.getConnection(dbp.getProperty("url"), dbp); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(dbp.getProperty("versionQuery")); if (rs.next()) { System.out.printf("Hello from %sn",rs.getString("version")); } rs.close(); st.close(); con.close(); } }
  • 29. www.percona.com29 Generic JDBC App Example import java.io.IOException; import java.sql.*; import java.util.Properties; public class DBHello { public static void main(String[] args) throws SQLException,ClassNotFoundException,IOException { Properties dbp = new Properties(); dbp.load(DBHello.class.getClassLoader() .getResourceAsStream("db.properties")); Class.forName(dbp.getProperty("class")); Connection con = DriverManager.getConnection(dbp.getProperty("url"), dbp); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(dbp.getProperty("versionQuery")); if (rs.next()) { System.out.printf("Hello from %sn",rs.getString("version")); } rs.close(); st.close(); con.close(); } }
  • 30. www.percona.com30 Generic JDBC App Example db.properties configured for MySQL: # driver class=com.mysql.jdbc.Driver # connection url url=jdbc:mysql://localhost user=user password=pwd # parameters autoReconnect=true useConfigs=maxPerformance # version query versionQuery=SELECT CONCAT_WS(' ',@@version_comment,@@version, @@version_compile_os,@@version_compile_machine) AS `version` Returns: Hello from MySQL Community Server (GPL) 5.6.23-log Linux x86_64
  • 31. www.percona.com31 Prepared Statements  Security – Better protection from SQL injection attacks, parameters are sent separately, escaping unnecessary  Performance – Prepared Statements are re-usable. Interpretation and Optimization happens only once.  More Performance – Combined with Pooling/Caching.  Use them whenever you can.
  • 32. www.percona.com32 Let's do something useful  Runs as a service, records storage capacity to a table  Runs as a report, outputs capacity growth over time  Load JDBC configuration from a Java properties file  PreparedStatement Query with ResultSet  Use and Reuse of PreparedStatement  Batch inserts using addBatch/executeBatch  Dynamic DDL creation DiskFreeChecker.java github.com/dbpercona/DiskFreeChecker
  • 33. www.percona.com33 Prepared Statement Query pst=con.prepareStatement( "SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?"); pst.setString(1, hostname); pst.setTimestamp(2, ts); rs=pst.executeQuery(); while (rs.next()) { DiskFreeEntry dfe=new DiskFreeEntry(); dfe.id = rs.getLong("id"); dfe.hostname = rs.getString("hostname"); dfe.fileSystemName = rs.getString("file_system_name"); dfe.totalSpace = rs.getLong("total_space"); dfe.spaceUsed = rs.getLong("space_used"); dfe.spaceFree = rs.getLong("space_free"); dfe.percentageUsed = rs.getBigDecimal("percentage_used"); dfe.fileSystemRoot = rs.getString("file_system_root"); dfe.when = rs.getTimestamp("file_system_root"); diskFreeEntries.put(dfe.fileSystemRoot,dfe); } rs.close(); pst.close();
  • 34. www.percona.com34 Prepared Statement Query pst=con.prepareStatement( "SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?"); pst.setString(1, hostname); pst.setTimestamp(2, ts); rs=pst.executeQuery(); while (rs.next()) { DiskFreeEntry dfe=new DiskFreeEntry(); dfe.id = rs.getLong("id"); dfe.hostname = rs.getString("hostname"); dfe.fileSystemName = rs.getString("file_system_name"); dfe.totalSpace = rs.getLong("total_space"); dfe.spaceUsed = rs.getLong("space_used"); dfe.spaceFree = rs.getLong("space_free"); dfe.percentageUsed = rs.getBigDecimal("percentage_used"); dfe.fileSystemRoot = rs.getString("file_system_root"); dfe.when = rs.getTimestamp("file_system_root"); diskFreeEntries.put(dfe.fileSystemRoot,dfe); } rs.close(); pst.close();
  • 35. www.percona.com35 Prepared Statement Query pst=con.prepareStatement( "SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?"); pst.setString(1, hostname); pst.setTimestamp(2, ts); rs=pst.executeQuery(); while (rs.next()) { DiskFreeEntry dfe=new DiskFreeEntry(); dfe.id = rs.getLong("id"); dfe.hostname = rs.getString("hostname"); dfe.fileSystemName = rs.getString("file_system_name"); dfe.totalSpace = rs.getLong("total_space"); dfe.spaceUsed = rs.getLong("space_used"); dfe.spaceFree = rs.getLong("space_free"); dfe.percentageUsed = rs.getBigDecimal("percentage_used"); dfe.fileSystemRoot = rs.getString("file_system_root"); dfe.when = rs.getTimestamp("file_system_root"); diskFreeEntries.put(dfe.fileSystemRoot,dfe); } rs.close(); pst.close();
  • 36. www.percona.com36 Prepared Statement Query pst=con.prepareStatement( "SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?"); pst.setString(1, hostname); pst.setTimestamp(2, ts); rs=pst.executeQuery(); while (rs.next()) { DiskFreeEntry dfe=new DiskFreeEntry(); dfe.id = rs.getLong("id"); dfe.hostname = rs.getString("hostname"); dfe.fileSystemName = rs.getString("file_system_name"); dfe.totalSpace = rs.getLong("total_space"); dfe.spaceUsed = rs.getLong("space_used"); dfe.spaceFree = rs.getLong("space_free"); dfe.percentageUsed = rs.getBigDecimal("percentage_used"); dfe.fileSystemRoot = rs.getString("file_system_root"); dfe.when = rs.getTimestamp("file_system_root"); diskFreeEntries.put(dfe.fileSystemRoot,dfe); } rs.close(); pst.close();
  • 37. www.percona.com37 Prepared Statement Query pst=con.prepareStatement( "SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?"); pst.setString(1, hostname); pst.setTimestamp(2, ts); rs=pst.executeQuery(); while (rs.next()) { DiskFreeEntry dfe=new DiskFreeEntry(); dfe.id = rs.getLong("id"); dfe.hostname = rs.getString("hostname"); dfe.fileSystemName = rs.getString("file_system_name"); dfe.totalSpace = rs.getLong("total_space"); dfe.spaceUsed = rs.getLong("space_used"); dfe.spaceFree = rs.getLong("space_free"); dfe.percentageUsed = rs.getBigDecimal("percentage_used"); dfe.fileSystemRoot = rs.getString("file_system_root"); dfe.when = rs.getTimestamp("file_system_root"); diskFreeEntries.put(dfe.fileSystemRoot,dfe); } rs.close(); pst.close();
  • 38. www.percona.com38 Prepared Statement Query pst=con.prepareStatement( "SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?"); pst.setString(1, hostname); pst.setTimestamp(2, ts); rs=pst.executeQuery(); while (rs.next()) { DiskFreeEntry dfe=new DiskFreeEntry(); dfe.id = rs.getLong("id"); dfe.hostname = rs.getString("hostname"); dfe.fileSystemName = rs.getString("file_system_name"); dfe.totalSpace = rs.getLong("total_space"); dfe.spaceUsed = rs.getLong("space_used"); dfe.spaceFree = rs.getLong("space_free"); dfe.percentageUsed = rs.getBigDecimal("percentage_used"); dfe.fileSystemRoot = rs.getString("file_system_root"); dfe.when = rs.getTimestamp("file_system_root"); diskFreeEntries.put(dfe.fileSystemRoot,dfe); } rs.close(); pst.close();
  • 39. www.percona.com39 Prepared Statement Query pst=con.prepareStatement( "SELECT * FROM diskfree WHERE `hostname` = ? AND `when` = ?"); pst.setString(1, hostname); pst.setTimestamp(2, ts); rs=pst.executeQuery(); while (rs.next()) { DiskFreeEntry dfe=new DiskFreeEntry(); dfe.id = rs.getLong("id"); dfe.hostname = rs.getString("hostname"); dfe.fileSystemName = rs.getString("file_system_name"); dfe.totalSpace = rs.getLong("total_space"); dfe.spaceUsed = rs.getLong("space_used"); dfe.spaceFree = rs.getLong("space_free"); dfe.percentageUsed = rs.getBigDecimal("percentage_used"); dfe.fileSystemRoot = rs.getString("file_system_root"); dfe.when = rs.getTimestamp("file_system_root"); diskFreeEntries.put(dfe.fileSystemRoot,dfe); } rs.close(); pst.close();
  • 40. www.percona.com40 Prepared Statement Reuse pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?"); // then pst.setBigDecimal(1, secondsBack); pst.setString(2, hostname); rs = pst.executeQuery(); if (rs.next()) { then = rs.getTimestamp(1); } rs.close(); // now pst.setInt(1, 0); rs = pst.executeQuery(); if (rs.next()) { now = rs.getTimestamp(1); } rs.close(); pst.close();
  • 41. www.percona.com41 Prepared Statement Reuse pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?"); // then pst.setBigDecimal(1, secondsBack); pst.setString(2, hostname); rs = pst.executeQuery(); if (rs.next()) { then = rs.getTimestamp(1); } rs.close(); // now pst.setInt(1, 0); rs = pst.executeQuery(); if (rs.next()) { now = rs.getTimestamp(1); } rs.close(); pst.close();
  • 42. www.percona.com42 Prepared Statement Reuse pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?"); // then pst.setBigDecimal(1, secondsBack); pst.setString(2, hostname); rs = pst.executeQuery(); if (rs.next()) { then = rs.getTimestamp(1); } rs.close(); // now pst.setInt(1, 0); rs = pst.executeQuery(); if (rs.next()) { now = rs.getTimestamp(1); } rs.close(); pst.close();
  • 43. www.percona.com43 Prepared Statement Reuse pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?"); // then pst.setBigDecimal(1, secondsBack); pst.setString(2, hostname); rs = pst.executeQuery(); if (rs.next()) { then = rs.getTimestamp(1); } rs.close(); // now pst.setInt(1, 0); rs = pst.executeQuery(); if (rs.next()) { now = rs.getTimestamp(1); } rs.close(); pst.close();
  • 44. www.percona.com44 Prepared Statement Reuse pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?"); // then pst.setBigDecimal(1, secondsBack); pst.setString(2, hostname); rs = pst.executeQuery(); if (rs.next()) { then = rs.getTimestamp(1); } rs.close(); // now pst.setInt(1, 0); rs = pst.executeQuery(); if (rs.next()) { now = rs.getTimestamp(1); } rs.close(); pst.close();
  • 45. www.percona.com45 Prepared Statement Reuse pst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?"); // then pst.setBigDecimal(1, secondsBack); pst.setString(2, hostname); rs = pst.executeQuery(); if (rs.next()) { then = rs.getTimestamp(1); } rs.close(); // now pst.setInt(1, 0); rs = pst.executeQuery(); if (rs.next()) { now = rs.getTimestamp(1); } rs.close(); pst.close();
  • 46. www.percona.com46 Prepared Statement Batches pst=con.prepareStatement( // prepare insert "INSERT INTO diskfree (`hostname`,`file_system_name`,"+ "`total_space`,`space_used`,`space_free`,`percentage_used`,"+ "`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)"); for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) { pst.setString ( 1, diskFreeEntry.hostname ); pst.setString ( 2, diskFreeEntry.fileSystemName ); pst.setLong ( 3, diskFreeEntry.totalSpace ); pst.setLong ( 4, diskFreeEntry.spaceUsed ); pst.setLong ( 5, diskFreeEntry.spaceFree ); pst.setBigDecimal( 6, diskFreeEntry.percentageUsed ); pst.setString ( 7, diskFreeEntry.fileSystemRoot ); pst.setTimestamp ( 8, when ); pst.addBatch(); // add to batch } int[] inserts=pst.executeBatch(); // execute batch int totalInserts=0; for (int i : inserts) totalInserts += i; // compute total
  • 47. www.percona.com47 Prepared Statement Batches pst=con.prepareStatement( // prepare insert "INSERT INTO diskfree (`hostname`,`file_system_name`,"+ "`total_space`,`space_used`,`space_free`,`percentage_used`,"+ "`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)"); for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) { pst.setString ( 1, diskFreeEntry.hostname ); pst.setString ( 2, diskFreeEntry.fileSystemName ); pst.setLong ( 3, diskFreeEntry.totalSpace ); pst.setLong ( 4, diskFreeEntry.spaceUsed ); pst.setLong ( 5, diskFreeEntry.spaceFree ); pst.setBigDecimal( 6, diskFreeEntry.percentageUsed ); pst.setString ( 7, diskFreeEntry.fileSystemRoot ); pst.setTimestamp ( 8, when ); pst.addBatch(); // add to batch } int[] inserts=pst.executeBatch(); // execute batch int totalInserts=0; for (int i : inserts) totalInserts += i; // compute total
  • 48. www.percona.com48 Prepared Statement Batches pst=con.prepareStatement( // prepare insert "INSERT INTO diskfree (`hostname`,`file_system_name`,"+ "`total_space`,`space_used`,`space_free`,`percentage_used`,"+ "`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)"); for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) { pst.setString ( 1, diskFreeEntry.hostname ); pst.setString ( 2, diskFreeEntry.fileSystemName ); pst.setLong ( 3, diskFreeEntry.totalSpace ); pst.setLong ( 4, diskFreeEntry.spaceUsed ); pst.setLong ( 5, diskFreeEntry.spaceFree ); pst.setBigDecimal( 6, diskFreeEntry.percentageUsed ); pst.setString ( 7, diskFreeEntry.fileSystemRoot ); pst.setTimestamp ( 8, when ); pst.addBatch(); // add to batch } int[] inserts=pst.executeBatch(); // execute batch int totalInserts=0; for (int i : inserts) totalInserts += i; // compute total
  • 49. www.percona.com49 Prepared Statement Batches pst=con.prepareStatement( // prepare insert "INSERT INTO diskfree (`hostname`,`file_system_name`,"+ "`total_space`,`space_used`,`space_free`,`percentage_used`,"+ "`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)"); for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) { pst.setString ( 1, diskFreeEntry.hostname ); pst.setString ( 2, diskFreeEntry.fileSystemName ); pst.setLong ( 3, diskFreeEntry.totalSpace ); pst.setLong ( 4, diskFreeEntry.spaceUsed ); pst.setLong ( 5, diskFreeEntry.spaceFree ); pst.setBigDecimal( 6, diskFreeEntry.percentageUsed ); pst.setString ( 7, diskFreeEntry.fileSystemRoot ); pst.setTimestamp ( 8, when ); pst.addBatch(); // add to batch } int[] inserts=pst.executeBatch(); // execute batch int totalInserts=0; for (int i : inserts) totalInserts += i; // compute total
  • 50. www.percona.com50 Prepared Statement Batches pst=con.prepareStatement( // prepare insert "INSERT INTO diskfree (`hostname`,`file_system_name`,"+ "`total_space`,`space_used`,`space_free`,`percentage_used`,"+ "`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)"); for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) { pst.setString ( 1, diskFreeEntry.hostname ); pst.setString ( 2, diskFreeEntry.fileSystemName ); pst.setLong ( 3, diskFreeEntry.totalSpace ); pst.setLong ( 4, diskFreeEntry.spaceUsed ); pst.setLong ( 5, diskFreeEntry.spaceFree ); pst.setBigDecimal( 6, diskFreeEntry.percentageUsed ); pst.setString ( 7, diskFreeEntry.fileSystemRoot ); pst.setTimestamp ( 8, when ); pst.addBatch(); // add to batch } int[] inserts=pst.executeBatch(); // execute batch int totalInserts=0; for (int i : inserts) totalInserts += i; // compute total
  • 51. www.percona.com51 Prepared Statement Batches pst=con.prepareStatement( // prepare insert "INSERT INTO diskfree (`hostname`,`file_system_name`,"+ "`total_space`,`space_used`,`space_free`,`percentage_used`,"+ "`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)"); for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) { pst.setString ( 1, diskFreeEntry.hostname ); pst.setString ( 2, diskFreeEntry.fileSystemName ); pst.setLong ( 3, diskFreeEntry.totalSpace ); pst.setLong ( 4, diskFreeEntry.spaceUsed ); pst.setLong ( 5, diskFreeEntry.spaceFree ); pst.setBigDecimal( 6, diskFreeEntry.percentageUsed ); pst.setString ( 7, diskFreeEntry.fileSystemRoot ); pst.setTimestamp ( 8, when ); pst.addBatch(); // add to batch } int[] inserts=pst.executeBatch(); // execute batch int totalInserts=0; for (int i : inserts) totalInserts += i; // compute total
  • 52. www.percona.com52 Prepared Statement Batches pst=con.prepareStatement( // prepare insert "INSERT INTO diskfree (`hostname`,`file_system_name`,"+ "`total_space`,`space_used`,`space_free`,`percentage_used`,"+ "`file_system_root`,`when`) VALUES (?,?,?,?,?,?,?,?)"); for (DiskFreeEntry diskFreeEntry : getDiskFreeEntries()) { pst.setString ( 1, diskFreeEntry.hostname ); pst.setString ( 2, diskFreeEntry.fileSystemName ); pst.setLong ( 3, diskFreeEntry.totalSpace ); pst.setLong ( 4, diskFreeEntry.spaceUsed ); pst.setLong ( 5, diskFreeEntry.spaceFree ); pst.setBigDecimal( 6, diskFreeEntry.percentageUsed ); pst.setString ( 7, diskFreeEntry.fileSystemRoot ); pst.setTimestamp ( 8, when ); pst.addBatch(); // add to batch } int[] inserts=pst.executeBatch(); // execute batch int totalInserts=0; for (int i : inserts) totalInserts += i; // compute total
  • 53. www.percona.com53 Prepared Statement Writes int keepDays=30; String strKeepDays=dbp.getProperty("keep.days"); if (strKeepDays != null) keepDays = new Integer(strKeepDays).intValue(); pst = con.prepareStatement( "DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)"); pst.setInt(1, keepDays); pst.execute(); int updateCount=pst.getUpdateCount(); if (updateCount > 0) System.out.println("Cleaned up "+updateCount+" old entries."); else System.out.println("No old entries to clean up."); pst.close();
  • 54. www.percona.com54 int keepDays=30; String strKeepDays=dbp.getProperty("keep.days"); if (strKeepDays != null) keepDays = new Integer(strKeepDays).intValue(); pst = con.prepareStatement( "DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)"); pst.setInt(1, keepDays); pst.execute(); int updateCount=pst.getUpdateCount(); if (updateCount > 0) System.out.println("Cleaned up "+updateCount+" old entries."); else System.out.println("No old entries to clean up."); pst.close(); Prepared Statement Writes
  • 55. www.percona.com55 Prepared Statement Writes int keepDays=30; String strKeepDays=dbp.getProperty("keep.days"); if (strKeepDays != null) keepDays = new Integer(strKeepDays).intValue(); pst = con.prepareStatement( "DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)"); pst.setInt(1, keepDays); pst.execute(); int updateCount=pst.getUpdateCount(); if (updateCount > 0) System.out.println("Cleaned up "+updateCount+" old entries."); else System.out.println("No old entries to clean up."); pst.close();
  • 56. www.percona.com56 Prepared Statement Writes int keepDays=30; String strKeepDays=dbp.getProperty("keep.days"); if (strKeepDays != null) keepDays = new Integer(strKeepDays).intValue(); pst = con.prepareStatement( "DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)"); pst.setInt(1, keepDays); pst.execute(); int updateCount=pst.getUpdateCount(); if (updateCount > 0) System.out.println("Cleaned up "+updateCount+" old entries."); else System.out.println("No old entries to clean up."); pst.close();
  • 57. www.percona.com57 Prepared Statement Writes int keepDays=30; String strKeepDays=dbp.getProperty("keep.days"); if (strKeepDays != null) keepDays = new Integer(strKeepDays).intValue(); pst = con.prepareStatement( "DELETE FROM diskfree WHERE `when` < ( NOW() - INTERVAL ? DAY)"); pst.setInt(1, keepDays); pst.execute(); int updateCount=pst.getUpdateCount(); if (updateCount > 0) System.out.println("Cleaned up "+updateCount+" old entries."); else System.out.println("No old entries to clean up."); pst.close();
  • 58. www.percona.com58 Performance parameters Parameter What it does cachePrepStmts=true If true, cache prepared statements on client side cacheCallableStmts=true If true, cache prepared stored procedure calls CacheServerConfiguration= true If true, reduces connect queries by caching server configuration variables. useLocalSessionState=true If true, reduces setup queries by using the local session state elideSetAutoCommits=true If true, only set autocommit if the server doesn't match the client autocommit setting. AlwaysSendSetIsolation= false If false, doesn't set the transaction isolation level on connect. Uses server default isolation level enableQueryTimeouts=false If false, disables query timeouts
  • 59. www.percona.com59 Performance parameters Parameter What it does cachePrepStmts=true If true, cache prepared statements on client side cacheCallableStmts=true If true, cache prepared stored procedure calls CacheServerConfiguration= true If true, reduces connect queries by caching server configuration variables. useLocalSessionState=true If true, reduces setup queries by using the local session state elideSetAutoCommits=true If true, only set autocommit if the server doesn't match the client autocommit setting. AlwaysSendSetIsolation= false If false, doesn't set the transaction isolation level on connect. Uses server default isolation level enableQueryTimeouts=false If false, disables query timeouts useConfigs=maxPerformance
  • 60. www.percona.com60 Debugging parameters Parameter What it does profileSQL=true If true, log query execution times to the configured logger. gatherPerfMetrics=true If true, collect performance metrics to the configured logger. useUsageAdvisor=true If true, inefficient use of JDBC and MySQL will logged to the configured logger as warnings. logSlowQueries=true If true, 'slow' queries will be logged to the configured logger (slowQueryThresholdMillis) explainSlowQueries=true If true, an 'EXPLAIN' statement for slow queries will be logged to the configured logger.
  • 61. www.percona.com61 Debugging parameters Parameter What it does profileSQL=true If true, log query execution times to the configured logger. gatherPerfMetrics=true If true, collect performance metrics to the configured logger. useUsageAdvisor=true If true, inefficient use of JDBC and MySQL will logged to the configured logger as warnings. logSlowQueries=true If true, 'slow' queries will be logged to the configured logger (slowQueryThresholdMillis) explainSlowQueries=true If true, an 'EXPLAIN' statement for slow queries will be logged to the configured logger. useConfigs=fullDebug
  • 63. www.percona.com63 Alternative JDBC Driver  MariaDB Java Client  Maintained-ed by MariaDB team  Fork from Drizzle JDBC  Stable release 1.1.8  Compatible with:  MySQL  Percona Server / PXC  MariaDB
  • 64. www.percona.com64 Alternative JDBC Driver  Pros  Maybe be faster in some cases  It is under active development  Cons  Not as feature rich  Not as mature
  • 65. www.percona.com65 What to learn about next  Connection Pooling  DBCP, C3P0, BoneCP  JNDI / Container Managed  DataSource, Spring  Object Relational Mapping  JPA, Hibernate, Spring

Notas del editor

  1. By a show of hands, how many people consider themselves Java Experts?, those who have some java experience? How many Java beginners (little or no experience). Likewise for MySQL, how many experts do we have, some experience, beginners.