A CallableStatement is used to call stored procedures in a database. The post (“JDBC Batch Update”) will give a simple example, and show how to use JDBC CallableStatement to call stored procedures.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package net.tecbar.jdbc.examples; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcCallableStatementExample1 { private final static String USERNAME = "root"; private final static String PASSWORD = ""; public static void main(String[] args) { JdbcCallableStatementExample1 instance = new JdbcCallableStatementExample1(); instance.getRecord(); } public void getRecord() { Connection conn = null; CallableStatement stmt = null; try{ // Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Open a connection (MySQL as example) conn = DriverManager.getConnection("jdbc:mysql://localhost/mytecbar", USERNAME, PASSWORD); // Execute a query (assuming you have a store procedure sproc defined) stmt = conn.prepareCall("{call sproc(?)}"); stmt.setInt(1, 3); // stmt.execute(); rs = stmt.executeQuery(); while(rs.next()) { System.out.println(rs.getString("name") + " : " + rs.getString("description")); } } catch(SQLException sle){ // process exception here sle.printStackTrace(); } catch(Exception e){ // process exception here e.printStackTrace(); } finally{ release(conn, stmt, null); } } public void release(Connection conn, Statement stmt, ResultSet rs) { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException ex) { // process exception here } } } |
Pingback: JDBC by Examples