在本文中,我们将使用JDBC API从Java应用程序调用MySQL数据库中存储的函数,即;使用CallableStatement 接口
1. 先决条件:
- Java JDK 1.8.0_77
- MySQL database 5.5.16
- Eclipse Luna IDE 4.4.0
- mysql-connector-java-5.1.38.jar file
2. 数据库参数:
让我们继续编写一个示例,以连接来自Java应用程序的MySQL数据库,以使用JDBC API调用或调用数据库存储函数。但在此之前,我们将列出连接数据库所需的内容
- 数据库服务器 IP 或地址(localhost)
- 服务器端口 (3306)
- 数据库名称 (PLAYER_INFO)
- 用户名(root)
- 密码 (root)
注意:所有粗体都是用于连接 MySQL 数据库的数据库值
3. 存储功能
- 这类似于存储过程,但有一个区别
- 该存储的函数始终返回一个值
- 而对于存储过程,我们必须注册OUT参数
3.1 使用存储函数的优点
- 提高性能,因为这些是预编译的
- 更快的执行速度
- 业务逻辑完全在数据库内部,具有额外的安全性
- 如果业务逻辑有任何更改,则所有更改都需要在数据库端完成,并且不会使Java代码变脏
- 存储函数: sfCountPlayerRecordinDB
use PLAYER_INFO; delimiter / CREATE FUNCTION sfCountPlayerRecordinDB() RETURNS INT BEGIN declare total int; select count(*) into total from player; return total; END; / delimiter ;
3.2 使用 JDBC 可调用语句接口调用存储函数
- 由于我们已准备好从Java应用程序连接MySQL数据库所需的东西
- 语法:要调用数据库存储函数,请使用以下语法
{? = call sfCountPlayerRecordinDB()}
让我们使用可调用语句接口编写一个简单的示例
InvokeStoredFunctionusJDBCCallableStatement.java
package in.bench.resources.mysql.db.proc;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class InvokeStoredFunctionUsingJDBCCallableStatement {
public static void main(String[] args) {
// variables
Connection connection = null;
CallableStatement callableStatement = null;
// Step 1: Loading or registering MySQL JDBC driver class
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException cnfex) {
System.out.println("Problem in loading MySQL JDBC driver");
cnfex.printStackTrace();
}
// Step 2: Opening database connection
try {
// Step 2.A: Create and get connection using DriverManager
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/PLAYER_INFO", "root", "root@123");
// Step 2.B: Creating JDBC CallableStatement
callableStatement = connection
.prepareCall("{? = call sfCountPlayerRecordinDB()}");
// register OUT parameter
callableStatement.registerOutParameter(1, Types.INTEGER);
// Step 2.C: Executing CallableStatement
callableStatement.execute();
// get count and print in console
int count = callableStatement.getInt(1);
System.out.println(
"Player count in PLAYER_INFO database is = " + count);
}
catch(SQLException sqlex){
sqlex.printStackTrace();
}
finally {
// Step 3: Closing database connection
try {
if(null != connection) {
// cleanup resources, once after processing
callableStatement.close();
// and then finally close connection
connection.close();
}
}
catch (SQLException sqlex) {
sqlex.printStackTrace();
}
}
}
}
输出:
Player count in PLAYER_INFO database is = 14