Przejdź do głównej zawartości

Stored Procedures - JDBC Java SQL

Stored Procedures:

  • group of SQL statements that perform a particular task 
  • Normally created by DBA
  • Can have any combination of input, output, and input/output parameters
Benefits:

To call stored procedure from Java

The JDBC API provides the CallableStatement

CallableStatement myCall = myConn.prepareCall("{call some_stored_procedure()}");
...
myCall.execute();

JDBC API parameter types
  • IN default
  • INOUT
  • OUT
Stored Procedure can return result sets


EXAMPLE: Created stored procedure on MySQL side - NAME: increase_salaries_for_department

DELIMITER $$
DROP PROCEDURE IF EXISTS `increase_salaries_for_department`$$

CREATE DEFINER=`student`@`localhost` PROCEDURE `increase_salaries_for_department`
(IN the_department VARCHAR(64), IN increase_amount DECIMAL(10,2))

BEGIN

UPDATE employees SET salary= salary + increase_amount where department=the_department;

END$$
DELIMITER ;

Java side:

                        // Get a connection to database
myConn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/newdb?autoReconnect=true&useSSL=false", "root", "Sasanka01");
                        // Values for parameters
String theDepartment = "Engineering";
int theIncreaseAmount = 10000;
// Show salaries BEFORE
System.out.println("Salaries BEFORE\n");
showSalaries(myConn, theDepartment);

// Prepare the stored procedure call
myStmt = myConn
.prepareCall("{call increase_salaries_for_department(?, ?)}");

// Set the parameters
myStmt.setString(1, theDepartment);
myStmt.setDouble(2, theIncreaseAmount);

// Call stored procedure
System.out.println("\n\nCalling stored procedure.  increase_salaries_for_department('" + theDepartment + "', " + theIncreaseAmount + ")");
                        //Execute statement
                        myStmt.execute();
System.out.println("Finished calling stored procedure");

// Show salaries AFTER
System.out.println("\n\nSalaries AFTER\n");
showSalaries(myConn, theDepartment);


INOUT parameters

Stored procedure developed for MySQL

PROCEDURE 'greet_the_department' ( INOUT department VARCHAR(64) )
BEGIN
     SET department = concat ('Hello to awesome ', department, 'team!' );
END

Java Coding

 // Prepare the stored procedure call
 myStmt = myConn.prepareCall("{call greet_the_department(?)}");

// Set the parameters
myStmt.registerOutParameter(1, Types.VARCHAR);
myStmt.setString(1, theDepartment);

// Call stored procedure
System.out.println("Calling stored procedure.  greet_the_department('" + theDepartment + "')");
myStmt.execute();
System.out.println("Finished calling stored procedure");
// Get the value of the INOUT parameter
String theResult = myStmt.getString(1);
System.out.println("\nThe result = " + theResult);

OUT Parameters
Stored procedure developed for MySQL

PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count FROM employees where department=the_department;

END;

Java Coding

 // Prepare the stored procedure call
 myStmt = myConn.prepareCall("{call get_count_for_department(?, ?)}");

// Set the parameters
myStmt.setString(1, "Engineering);
myStmt.registerOutParameter(2, Types.INTEGER);

//Call stored procedure
myStmt = execute();

//Get the value of the OUT parameter
int theCount = myStmt.getInt(2)

Komentarze

Popularne posty z tego bloga

Java - variables , data types

Data Types Data types in Java are classified in to types: Primitive - which include Integer, Character, Boolean and Floating Point Non-primitive - which includes Classes, Interfaces and Arrays Integer : byte 1 byte short 2 bytes int 4 bytes long 8 bytes Floating Point : number + fractional parts  float double Character : stores character Boolean : hold true false value Variables  Instance Variables (non-Static Fields) -  Objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Class Variables - Static Fields - any field with static modifier says that there is only one copy of this variable in existence static int myClassVariable = 6;  Local Variables - a method stores it's temporary state of local variables int count=0; Parameters - variables which will be passed to the methods of a class

Inserting Data into SQL Database with Java

Inserting Data into SQL Database with Java Java Documentation - Processing SQL statements with JDBC  Process: Get connection to database Create a statement Execute SQL query import java.sql.*; /**  *  * @author www.luv2code.com  *  */ public class JdbcTest { public static void main(String[] args) throws SQLException { Connection myConn = null; Statement myStmt = null; ResultSet myRs = null; String dbUrl = "jdbc:mysql://localhost:3306/demo ?autoReconnect=true&useSSL=false "; String user = "root"; String pass = "Sasanka01"; try { // 1. Get a connection to database myConn = DriverManager.getConnection(dbUrl, user, pass); System.out.println("Database connection successfully created"); // 2. Create a statement myStmt = myConn.createStatement(); int rowsAffected = myStmt.executeUpdate(                          "...