Stored procedures using JDBC

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_34017326/article/details/51550120

Use the mysql jdbc stored procedure call

CallableStatement JDBC call a stored procedure using the core interface, use the interface steps:
    1. Write call a stored procedure sql statement, there are two forms:
        Call procedure_name (arg1, arg2, ......)
        = Call procedure_name (arg1, arg2? , ......)
       parameter to call the stored procedure sql statement can be used? as a placeholder


   2. Create a CallableStatement object
       Connection.prepareCall (String sql)


   3. Set the parameter values of the parameters in the order
       1) If the IN type parameter, the value of the parameter setting method using setXxx
       2) If the type is the OUT parameter, using registerOutParameter (int parameterIndex, int sqlType) Parameter Type Register Output


   4. Call execute () method executes a stored procedure


   5. Obtain the execution result stored procedure
       1) values of the parameters acquired by the OUT type getXxx method
       obtaining the result set object 2) if the stored procedure returns a result set, using the getResultSet () method, according to the traditional way of obtaining the result set data


example:

Writing stored procedures

delimiter '//';

create procedure proc1(in user_name varchar(20),out user_password varchar(32))
begin
	select password into user_password from tb_admin where name=user_name;
end//

delimiter ';'//

java code:

import java.sql.*;

public class CallTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql://localhost:3306/db_spring";
			String name="root";
			String password="123456";
			Connection con=DriverManager.getConnection(url, name, password);
			String sql="call proc1(?,?)";
			CallableStatement cs=con.prepareCall(sql);
			cs.setString(1, "zhangsan");
			cs.registerOutParameter(2, Types.VARCHAR);
			cs.execute();
			System.out.println(cs.getString(2));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}



Guess you like

Origin blog.csdn.net/qq_34017326/article/details/51550120