前言
关于Mysql-JDBC的使用
JDBC
JDBC(Java Database Connectivity)是java应用统一访问数据库层的api。
JDK | JDBC Version | JSR Specification |
---|---|---|
jdk8 | JDBC 4.2 | JSR 221 |
jdk7 | JDBC 4.1 | JSR 221 |
jdk6 | JDBC 4.0 | JSR 221 |
Mysql JDBC
Mysql-JDBC是用于mysql的JDBC驱动
URL
Mysql Connection URL 格式
1 | jdbc:mysql://[host][:port]/[database][?property1][=value1]... |
样例
1 | jdbc:mysql://localhost:3306/testDb?user=root&password=123456 |
加载
Class.forName
1
2//Load the MySQL JDBC driver,前提是mysql driver jar存在
Class.forName("com.mysql.jdbc.Driver");system prperties
1
-Djdbc.drivers="com.mysql.jdbc.Driver"
自动(驱动自定义: META-INF/services/jdbc.sql.Driver)
1
//JDK8会自动加载类路径下存在的Mysql Jdbc Driver。
连接
建立connection的两种方式:
by DriverManager
1
2
3
4
5Connection con = DriverManager.getConnection(String mysqlConnectionUrl);
Connection con = DriverManager.getConnection(String mysqlConnectionUrl, Properties info)
Connection con = DriverManager.getConnection(String mysqlConnectionUrl, String user, String password)by DataSource
1
dataSource.getConnection
Experiments
类 | 功能 |
---|---|
JdbcCase1 | list jdbc dirvers |
JdbcCase2 | build connection by DriverManager build connection by DataSource |
JdbcCase3 | java.sql.Statement api usage |
JdbcCase | java.sql.PreparedStatement api usage |
JdbcCase5 | java.sql.PreparedStatement Insert Performance |
Statement
使用Statement处理SQL.
1 | Statement statement = connection.createStatement(); |
PreparedStatement
If you have a SQL statement that needs to be executed multiple times, it is more efficient to use a JDBC PreparedStatement object to run it.
JDBC PreparedStatement features:
- SQL statements PreparedStatement objects are pre-compiled on the database server side.
- IN parameters are supported in SQL statements in PreparedStatement objects.
- Batch execution mode is supported to run the run SQL statement multiple times in a single transaction.
基本语法
To make a PreparedStatement object more flexible, you can add parameters to the embedded SQL statement with question marks (?).
1 | //by?符号 |
批量处理
1 | ps.setXXX(...); // Set parameters for the first copy |
性能对比
结论: If you have a SQL statement that needs to be executed multiple times, it is more efficient to use a JDBC PreparedStatement object to run it.
1 | 551 ms used when insert 100 records by ResultSet. |
CallableStatement
CallableStatement : 支持调用存储过程,提供了对输出和输入/输出参数(INOUT)的支持;
- A JDBC CallableStatement object allows you to call stored procedures in the database server.
- IN and OUT parameters can be passed to stored procedures from JDBC CallableStatement objects.