34 using mysql with java

71
David Bennett QA Engineer April 15 th , 2015 Using MySQL with Java Q2 2014

Transcript of 34 using mysql with java

Page 1: 34 using mysql with java

David BennettQA Engineer

April 15th, 2015

Using MySQL with JavaQ2 2014

Page 2: 34 using mysql with java

www.percona.com2

Who are you?

● Java Experts, Intermediate, Beginners

● MySQL Experts, Intermediate, Beginners

● Developers, DBAs, System Admins

● Just interested

Page 3: 34 using mysql with java

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

Page 4: 34 using mysql with java

www.percona.com4

Basic Topology

Java Application(Web, Service, Desktop)

Java Runtime Engine(JRE)

JDBC Interface

JDBC Driver (Connector/J)

MySQL

Page 5: 34 using mysql with java

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.

Page 6: 34 using mysql with java

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

Page 7: 34 using mysql with java

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(); }}

Page 8: 34 using mysql with java

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(); }}

Page 9: 34 using mysql with java

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(); }}

Page 10: 34 using mysql with java

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(); }}

Page 11: 34 using mysql with java

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(); }}

Page 12: 34 using mysql with java

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(); }}

Page 13: 34 using mysql with java

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(); }}

Page 14: 34 using mysql with java

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(); }}

Page 15: 34 using mysql with java

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(); }}

Page 16: 34 using mysql with java

16 www.percona.com

Page 17: 34 using mysql with java

17 www.percona.com

Page 18: 34 using mysql with java

18 www.percona.com

Page 19: 34 using mysql with java

19 www.percona.com

Page 20: 34 using mysql with java

20 www.percona.com

Page 21: 34 using mysql with java

21 www.percona.com

Page 22: 34 using mysql with java

www.percona.com22

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...

Page 23: 34 using mysql with java

www.percona.com23

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://dbserverConnect 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/mydbConnect the MySQL server dbserver on port 3307 using database mydb.

jdbc:mysql://dbserver/mydbConnect the MySQL server dbserver on port 3306 using database mydb.

Page 24: 34 using mysql with java

www.percona.com24

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://dbserverConnect 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/mydbConnect the MySQL server dbserver on port 3307 using database mydb.

jdbc:mysql://dbserver/mydbConnect the MySQL server dbserver on port 3306 using database mydb.

Page 25: 34 using mysql with java

www.percona.com25

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://dbserverConnect 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/mydbConnect the MySQL server dbserver on port 3307 using database mydb.

jdbc:mysql://dbserver/mydbConnect the MySQL server dbserver on port 3306 using database mydb.

Page 26: 34 using mysql with java

www.percona.com26

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://dbserverConnect 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/mydbConnect the MySQL server dbserver on port 3307 using database mydb.

jdbc:mysql://dbserver/mydbConnect the MySQL server dbserver on port 3306 using database mydb.

Page 27: 34 using mysql with java

www.percona.com27

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://dbserverConnect 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/mydbConnect the MySQL server dbserver on port 3307 using database mydb.

jdbc:mysql://dbserver/mydbConnect the MySQL server dbserver on port 3306 using database mydb.

Page 28: 34 using mysql with java

www.percona.com28

Connector/J parametersPassing 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:

Page 29: 34 using mysql with java

www.percona.com29

Connector/J parametersPassing 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:

Page 30: 34 using mysql with java

www.percona.com30

Connector/J parametersPassing 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:

Page 31: 34 using mysql with java

www.percona.com31

Connector/J parametersPassing 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:

Page 32: 34 using mysql with java

www.percona.com32

Generic JDBC App Exampleimport 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 %s\n",rs.getString("version")); } rs.close(); st.close(); con.close(); }}

Page 33: 34 using mysql with java

www.percona.com33

Generic JDBC App Exampleimport 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 %s\n",rs.getString("version")); } rs.close(); st.close(); con.close(); }}

Page 34: 34 using mysql with java

www.percona.com34

Generic JDBC App Exampleimport 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 %s\n",rs.getString("version")); } rs.close(); st.close(); con.close(); }}

Page 35: 34 using mysql with java

www.percona.com35

Generic JDBC App Exampledb.properties configured for MySQL:# driverclass=com.mysql.jdbc.Driver# connection urlurl=jdbc:mysql://localhostuser=userpassword=pwd# parametersautoReconnect=trueuseConfigs=maxPerformance# version queryversionQuery=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

Page 36: 34 using mysql with java

www.percona.com36

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.

Page 37: 34 using mysql with java

www.percona.com37

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.javagithub.com/dbpercona/DiskFreeChecker

Page 38: 34 using mysql with java

www.percona.com38

Prepared Statement Querypst=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();

Page 39: 34 using mysql with java

www.percona.com39

Prepared Statement Querypst=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();

Page 40: 34 using mysql with java

www.percona.com40

Prepared Statement Querypst=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();

Page 41: 34 using mysql with java

www.percona.com41

Prepared Statement Querypst=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();

Page 42: 34 using mysql with java

www.percona.com42

Prepared Statement Querypst=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();

Page 43: 34 using mysql with java

www.percona.com43

Prepared Statement Querypst=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();

Page 44: 34 using mysql with java

www.percona.com44

Prepared Statement Querypst=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();

Page 45: 34 using mysql with java

www.percona.com45

Prepared Statement Reusepst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?");// thenpst.setBigDecimal(1, secondsBack);pst.setString(2, hostname);rs = pst.executeQuery();if (rs.next()) { then = rs.getTimestamp(1);}rs.close();// nowpst.setInt(1, 0);rs = pst.executeQuery();if (rs.next()) { now = rs.getTimestamp(1);}rs.close();pst.close();

Page 46: 34 using mysql with java

www.percona.com46

Prepared Statement Reusepst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?");// thenpst.setBigDecimal(1, secondsBack);pst.setString(2, hostname);rs = pst.executeQuery();if (rs.next()) { then = rs.getTimestamp(1);}rs.close();// nowpst.setInt(1, 0);rs = pst.executeQuery();if (rs.next()) { now = rs.getTimestamp(1);}rs.close();pst.close();

Page 47: 34 using mysql with java

www.percona.com47

Prepared Statement Reusepst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?");// thenpst.setBigDecimal(1, secondsBack);pst.setString(2, hostname);rs = pst.executeQuery();if (rs.next()) { then = rs.getTimestamp(1);}rs.close();// nowpst.setInt(1, 0);rs = pst.executeQuery();if (rs.next()) { now = rs.getTimestamp(1);}rs.close();pst.close();

Page 48: 34 using mysql with java

www.percona.com48

Prepared Statement Reusepst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?");// thenpst.setBigDecimal(1, secondsBack);pst.setString(2, hostname);rs = pst.executeQuery();if (rs.next()) { then = rs.getTimestamp(1);}rs.close();// nowpst.setInt(1, 0);rs = pst.executeQuery();if (rs.next()) { now = rs.getTimestamp(1);}rs.close();pst.close();

Page 49: 34 using mysql with java

www.percona.com49

Prepared Statement Reusepst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?");// thenpst.setBigDecimal(1, secondsBack);pst.setString(2, hostname);rs = pst.executeQuery();if (rs.next()) { then = rs.getTimestamp(1);}rs.close();// nowpst.setInt(1, 0);rs = pst.executeQuery();if (rs.next()) { now = rs.getTimestamp(1);}rs.close();pst.close();

Page 50: 34 using mysql with java

www.percona.com50

Prepared Statement Reusepst = con.prepareStatement("SELECT MAX(`when`) FROM diskfree " + "WHERE `when` < ( NOW() - INTERVAL ? SECOND ) " + "AND `hostname` = ?");// thenpst.setBigDecimal(1, secondsBack);pst.setString(2, hostname);rs = pst.executeQuery();if (rs.next()) { then = rs.getTimestamp(1);}rs.close();// nowpst.setInt(1, 0);rs = pst.executeQuery();if (rs.next()) { now = rs.getTimestamp(1);}rs.close();pst.close();

Page 51: 34 using mysql with java

www.percona.com51

Prepared Statement Batchespst=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 batchint totalInserts=0;for (int i : inserts) totalInserts += i; // compute total

Page 52: 34 using mysql with java

www.percona.com52

Prepared Statement Batchespst=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 batchint totalInserts=0;for (int i : inserts) totalInserts += i; // compute total

Page 53: 34 using mysql with java

www.percona.com53

Prepared Statement Batchespst=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 batchint totalInserts=0;for (int i : inserts) totalInserts += i; // compute total

Page 54: 34 using mysql with java

www.percona.com54

Prepared Statement Batchespst=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 batchint totalInserts=0;for (int i : inserts) totalInserts += i; // compute total

Page 55: 34 using mysql with java

www.percona.com55

Prepared Statement Batchespst=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 batchint totalInserts=0;for (int i : inserts) totalInserts += i; // compute total

Page 56: 34 using mysql with java

www.percona.com56

Prepared Statement Batchespst=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 batchint totalInserts=0;for (int i : inserts) totalInserts += i; // compute total

Page 57: 34 using mysql with java

www.percona.com57

Prepared Statement Batchespst=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 batchint totalInserts=0;for (int i : inserts) totalInserts += i; // compute total

Page 58: 34 using mysql with java

www.percona.com58

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();

Page 59: 34 using mysql with java

www.percona.com59

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

Page 60: 34 using mysql with java

www.percona.com60

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();

Page 61: 34 using mysql with java

www.percona.com61

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();

Page 62: 34 using mysql with java

www.percona.com62

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();

Page 63: 34 using mysql with java

www.percona.com63

Performance parameters

Parameter What it doescachePrepStmts=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

Page 64: 34 using mysql with java

www.percona.com64

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

Page 65: 34 using mysql with java

www.percona.com65

Debugging parameters

Parameter What it doesprofileSQL=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.

Page 66: 34 using mysql with java

www.percona.com66

Debugging parameters

Parameter What it doesprofileSQL=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

Page 67: 34 using mysql with java

www.percona.com67

Other Handy Parameters

●autoReconnect

●characterEncoding

●useInformationSchema

●maxRows

Page 68: 34 using mysql with java

www.percona.com68

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

Page 69: 34 using mysql with java

www.percona.com69

Alternative JDBC Driver

● Pros Maybe be faster in some cases It is under active development

Cons Not as feature rich Not as mature

Page 70: 34 using mysql with java

www.percona.com70

What to learn about next

● Connection Pooling

● DBCP, C3P0, BoneCP

● JNDI / Container Managed

● DataSource, Spring

● Object Relational Mapping

● JPA, Hibernate, Spring

Page 71: 34 using mysql with java

www.percona.com71 www.percona.com

THANK YOU