Skip to content

Instantly share code, notes, and snippets.

@juandbc
Last active July 24, 2019 18:39
Show Gist options
  • Save juandbc/7e8b1da33863af9eae9d9a4e1b669047 to your computer and use it in GitHub Desktop.
Save juandbc/7e8b1da33863af9eae9d9a4e1b669047 to your computer and use it in GitHub Desktop.
How to execute stored procedure with JDBC
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