Last active
July 24, 2019 18:39
-
-
Save juandbc/7e8b1da33863af9eae9d9a4e1b669047 to your computer and use it in GitHub Desktop.
How to execute stored procedure with JDBC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.*; | |
public class Main { | |
public static void main(String[] args) { | |
String sql = "{? = call fn_test()}"; | |
try (Connection conn = getConnection(); CallableStatement callableStatement = conn.prepareCall(sql); | |
PreparedStatement preparedStatement = conn.prepareStatement("select fn_test()")) { | |
// Execute stored procedured CallableStatement (recommend way) | |
callableStatement.registerOutParameter(1, Types.VARCHAR); | |
callableStatement.execute(); | |
System.out.println("Response: " + callableStatement.getString(1)); | |
// Execute stored procedured using PreparedStatement | |
ResultSet rs = preparedStatement.executeQuery(); | |
// ResultSet rs = preparedStatement.getResultSet(); | |
rs.next(); | |
System.out.println("Response: " + rs.getString(1)); | |
rs.close(); | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
System.err.println("Error al conectarse: " + e.getSQLState() + "-" + e.getMessage()); | |
} catch (NullPointerException e) { | |
e.printStackTrace(); | |
System.err.println("Error al conectarse: " + e.getMessage()); | |
} | |
} | |
static Connection getConnection() throws SQLException { | |
return DriverManager.getConnection("jdbc:postgresql://localhost/dbtest", "juan", "12345"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment