1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Java使用JDBC调用Mysql函数和存储过程

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

时间:2021-04-22 07:18:32

相关推荐

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

文章目录

前言一、举例说明二、主要代码如下

前言

之前使用过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 DriverDriverManager.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 statementcstmt.execute();//打印出输出的值System.out.print("Date of birth: "+cstmt.getDate(1));}}

最后输出:

Connection established…

Date of birth: 1989-09-26

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。