Home > Database > Mysql Tutorial > body text

java mysql stored procedure

王林
Release: 2023-05-20 13:37:08
Original
586 people have browsed it

Java and MySQL are two widely used technologies. When using them, we often need to use stored procedures to process data. Stored procedures are reusable blocks of code defined in a database that can be called when needed to perform specific tasks. This article will introduce stored procedures in Java and MySQL, including how to create and call them.

1. What is a MySQL stored procedure?

In MySQL, a stored procedure is a collection of predefined SQL statements that are combined in a certain logical order to form a reusable and executable process. Stored procedures are often used to process complex business logic or perform batch operations on data. Different from ordinary SQL statements, stored procedures can accept parameters and return data, which makes stored procedures more flexible and efficient when processing complex business logic.

2. How to create a MySQL stored procedure

In MySQL, we can use the CREATE PROCEDURE statement to create a stored procedure. The basic syntax of the CREATE PROCEDURE statement is as follows:

CREATE PROCEDURE procedure_name ([IN | OUT | INOUT] parameter_name data_type[, ...])
BEGIN
    -- 存储过程的SQL语句块
END
Copy after login

Among them, procedure_name is the name of the stored procedure, parameter_name is the parameter name of the stored procedure, and data_type is the data type of the parameter. The SQL statement block in the stored procedure is placed between BEGIN and END.

The following is a simple example that demonstrates how to create a stored procedure that calculates the circumference and area of ​​a circle:

CREATE PROCEDURE calc_circle(IN r INT, OUT circumference FLOAT, OUT area FLOAT)
BEGIN
    SET circumference = 2 * PI() * r;
    SET area = PI() * r * r;
END
Copy after login

This stored procedure accepts an integer parameter named r and returns the circle perimeter and area. In the stored procedure, we use MySQL's built-in PI() function to calculate pi. Circumference and area are the output parameters of perimeter and area respectively. We use the SET statement to set their values ​​to the corresponding calculation results.

3. How to call MySQL stored procedure

Once we create a stored procedure in MySQL, we can call it in Java. We can use JDBC (Java Database Connectivity) technology to connect to the MySQL database and use precompiled statements to call stored procedures. The following is a basic Java code example that demonstrates how to call the calc_circle stored procedure just created:

import java.sql.*;

public class CallSPDemo {
    public static void main(String[] args) {
        Connection conn = null;
        CallableStatement cs = null;
        
        try {
            // 连接MySQL数据库
            String url = "jdbc:mysql://localhost:3306/test";
            String user = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url, user, password);
            
            // 创建CallableStatement对象
            String sp = "{CALL calc_circle(?, ?, ?)}";
            cs = conn.prepareCall(sp);
            
            // 设置输入参数
            cs.setInt(1, 5);
            
            // 设置输出参数类型
            cs.registerOutParameter(2, Types.FLOAT);
            cs.registerOutParameter(3, Types.FLOAT);
            
            // 执行存储过程
            cs.execute();
            
            // 获取输出参数值
            float circum = cs.getFloat(2);
            float area = cs.getFloat(3);
            
            // 输出结果
            System.out.println("Circumference: " + circum);
            System.out.println("Area: " + area);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (cs != null) cs.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
Copy after login

In the code, we use the Connection and CallableStatement classes in the java.sql package to connect to the MySQL database and call the storage process. In the main() method, we first define a Connection object and a CallableStatement object. Then, we connected to the MySQL database and created a CallableStatement object through the prepareCall() method. When creating a CallableStatement object, we use the same syntax as when creating a stored procedure to define the stored procedure name and parameters.

Next, we set the value of the input parameter r of the stored procedure to 5 through the setInt() method. Then, we use the registerOutParameter() method to define the output parameter type of the result set, here it is the FLOAT type. Finally, we execute the stored procedure using the execute() method and get the value of the output parameter using the getFloat() method. Note that we need to execute the stored procedure before getting the value of the output parameter.

Finally, we output the calculated circumference and area of ​​the circle.

4. Advantages of stored procedures

The advantage of using MySQL stored procedures is that they can well separate business logic from database operations and achieve code reuse. In addition, stored procedures can also improve database performance and security.

First of all, stored procedures can improve database performance because when stored procedures are executed, they are precompiled and cached in the server, thus speeding up execution. In addition, when using stored procedures, we can merge multiple database operations together, thereby reducing the number of database connections and disconnections and greatly improving database performance.

Secondly, through stored procedures, we can control data access in the database, thus improving the security of the database. For example, we can restrict access to certain sensitive data tables and only allow authorized users to execute stored procedures to access them.

In summary, MySQL stored procedures are a very useful technology that allows us to better process and manage data. By learning and mastering the usage of stored procedures, we can improve our database development and maintenance capabilities to better serve our business needs.

The above is the detailed content of java mysql stored procedure. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!