Master java skills

Call stored procedure in java

Step 1: Create a Doctor table

CREATE TABLE doctor (
  id int DEFAULT NULL,
  name varchar(100) DEFAULT NULL,
  department varchar(100) DEFAULT NULL,
  city varchar(100) DEFAULT NULL,
  salary int DEFAULT NULL,
  country varchar(100) DEFAULT NULL
)

Doctor table records

Step 2: Create a procedure in mysql database.

DELIMITER &&
CREATE PROCEDURE get_doc_details_in (IN var int)
begin
select * from doctor where salary > var;
end &&

Step 3: Write java class

package com.javatrainingschool;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProcedureExample {

	public static void main(String[] args) throws SQLException {
		getDoctorDetails(100000);
	}

	public static void getDoctorDetails(int salary) throws SQLException {
		//
		String query = "{ call get_doc_details_in(?) }";
		ResultSet rs;

		Connection conn = JDBCUtil.getConnection();
		CallableStatement stmt = conn.prepareCall(query);

		stmt.setInt(1, salary);

		rs = stmt.executeQuery();
		
		int noOfRecords = 0;
		while (rs.next()) {
			System.out.println(String.format("%s - %s", rs.getString("name") + " " + rs.getString("department"),
					rs.getString("city")));
			
			noOfRecords++;
		}
		System.out.println(noOfRecords + " records found");
	}
}

JDBCUtil class

package com.javatrainingschool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {

	public static Connection getConnection() {
		
		// Load jdbc the driver
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		// Get a connection object
		Connection con = null;
		try {
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db", "root", "password123");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return con;
	}
}

Output: