Java uses JDBC to call Mysql functions and stored procedures


foreword

I have used mybatis and mybatis plus to call database functions and stored procedures before. This is also a widely used and popular method at present, but today I encountered a requirement to add function calls to a project. This project is not using mybatis. It's JPA, so I want to find out how to use JPA to call functions, but it seems that there is no particularly good way (maybe I didn't find it).
Later, I found an English answer, using JDBC, and then I tried it to realize the function, and wrote an article to record it.


1. Examples

For example, we have this table, and now the test uses the function to find out the data we want from this table
±-------±-----------±------- -------+
| Name | DOB | Location |
±-------±-----------±------------- -+
| Amit | 1989-09-26 | Hyderabad |
| Sumith |
1989-09-01
| -----±---------------+

函数如下:
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

2. The main code is as follows

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));
	}
}

Final output:
Connection established...
Date of birth: 1989-09-26

Guess you like

Origin blog.csdn.net/sunzixiao/article/details/127792949