PostgreSQL JDBC: Call Stored Functions
Summary: in this tutorial, you will learn how to call PostgreSQL stored functions using JDBC.
Calling a built-in stored function example
We will call a built-in string function initcap()
that capitalizes the first letter of each word in a string.
To call the initcap()
function, you follow these steps:
- First, establish a database connection.
- Second, create a
CallableStatement
object by calling theprepareCall()
method of theConnection
object. - Register
OUT
parameters if applicable. - Bind values to the statement if applicable.
- Third, execute the function call and obtain the result.
The following example creates a new class named Util
and defines a static method properCase()
that calls the initcap()
function in PostgreSQL:
The following illustrates how to use the properCase()
method of the Util
class:
Output:
Calling a stored function example
Let’s take an example of calling a stored function in PostgreSQL from a Java program using JDBC.
Creating a stored function
First, open Command Prompt on Windows or Terminal on Unix-like systems and connect to the sales database on your PostgreSQL server:
Second, create a function that finds the products by name based on a specified pattern:
Third, exit the psql:
Calling a stored function
The following defines the findByName()
method in the ProductDB
class that calls the find_products
stored function to find the products by names based on a pattern:
The following uses the findByName()
method of the ProductDB
class to search for products with the name containing the string "phone"
:
Output:
Summary
- Use the
CallableStatement
to call a built-in function from PostgreSQL.