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

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if

String-2 > xyzThere - java

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.  xyzThere("abcxyz") → true xyzThere("abc.xyz") → false xyzThere("xyz.abc") → true Definiujemy loop ktory sprawdza za kazdym podejsciem czy kolejne indexy i,i+1 oraz i+2 i zdefiniowane dla nich char.  Nalezy tu pamietac ze jesli sprawdamy po indeksach np i+2 to tzreba zostawic "miejsce" na koncu aby nie bylo outOfBoudnExeption tj przekroczenia rlugosci stringa. Jezeli pierwszy warunek jest spelniony tj mamy na kolejnych indexach interesujace nas char-y sprawdzamy czy na poprzedzajacych nasza trojkę indexach pojawia sie "." zaczynamy od indexu 0 - tzreba to uwzglednić w warunku tj albo index 0 == 0 lub i-1 == 0 public boolean xyzThere ( String str ) { int len = str . length () - 2 ; for ( int i = 0 ; i < len ; i...

Learning by doing - Java - 50+ Interview Questions for Programmers

Learning by doing - Java - 50+ Interview Questions for Programmers 50+ Interview questions for 50+ days ? We will see ;) Risky resolution but method "learning by doing" is great!! First are coming questions regarding Arrays: How do you find the missing number in a given integer array of 1 to 100? ( solution ) How do you find the duplicate number on a given integer array? ( solution ) How do you find the largest and smallest number in an unsorted integer array? ( solution ) How do you find all pairs of an integer array whose sum is equal to a given number? ( solution ) How do you find duplicate numbers in an array if it contains multiple duplicates? ( solution ) How are duplicates removed from a given array in Java? ( solution ) How is an integer array sorted in place using the quicksort algorithm? ( solution ) How do you remove duplicates from an array in place? ( solution ) How do you reverse an array in place in Java? ( solution ) How are duplicates remov...