Java使用JDBC调用Mysql函数和存储过程

2 篇文章 0 订阅
2 篇文章 0 订阅


前言

之前使用过mybatis和mybatis plus来调用数据库函数和存储过程,这也是目前使用比较广泛和流行的方法,但是今天遇到一个要求就是在一个项目中添加函数调用的功能,这个项目不是使用的mybatis,而是JPA,所以想找一下如何使用JPA调用函数的方法,但是好像没有特别好的方法(可能是我没找到)。
后来找到一篇英文解答,使用的是JDBC,然后我试了一下是可以实现功能的,写篇文章记录一下。


一、举例说明

比如我们有这个表,现在测试用函数从这个表中查出我们想要的数据
±-------±-----------±---------------+
| Name | DOB | Location |
±-------±-----------±---------------+
| Amit | 1989-09-26 | Hyderabad |
| Sumith | 1989-09-01 | Vishakhapatnam |
| Sudha | 1980-09-01 | Vijayawada |
±-------±-----------±---------------+

函数如下:
CREATE FUNCTION getDob(emp_name VARCHAR(50)) RETURNS DATE
BEGIN
declare dateOfBirth DATE;
select DOB into dateOfBirth from EMP where Name = emp_name;
return dateOfBirth;
END

二、主要代码如下

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class CallingFunctionsExample {
   public static void main(String args[]) throws SQLException {
	    //Registering the Driver
	    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
	    //Getting the connection
	    //tableName替换为自己的数据库的名字
	    String mysqlUrl = "jdbc:mysql://localhost/tableName";
	    //root替换为自己的数据库的账号名字,12345678为密码
	    Connection con = DriverManager.getConnection(mysqlUrl, "root", "12345678");
	    System.out.println("Connection established......");
	    //Preparing a CallableStatement to call a function
	    //function为所要调用的函数的名字
	    //(?)表示输入参数
	    CallableStatement cstmt = con.prepareCall("{? = call getDob(?)}");
	    //Registering the out parameter of the function (return type)
	    /Types.DATE表示输出参数的类型
	    cstmt.registerOutParameter(1, Types.DATE);
	    //Setting the input parameters of the function
	    //Amit表示输入参数
	    cstmt.setString(2, "Amit");
	    //Executing the statement
	    cstmt.execute();
	    //打印出输出的值
	    System.out.print("Date of birth: "+cstmt.getDate(1));
	}
}

最后输出:
Connection established…
Date of birth: 1989-09-26

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值