This document discusses using Java with MySQL. It begins with an introduction to JDBC and the Connector/J driver. It then provides examples of connecting to MySQL from Java using the JDBC URL and driver, executing queries, and using prepared statements. It demonstrates how to load configuration from properties and retrieve data from a result set. The examples show basic CRUD operations and utilizing prepared statements for security and performance.
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
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();
}
}
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
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
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
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.