Java SQL Execute executeSP(Connection conn, String spName, Object... parameters)

Here you can find the source of executeSP(Connection conn, String spName, Object... parameters)

Description

execute SP

License

Apache License

Declaration

public static int executeSP(Connection conn, String spName, Object... parameters) throws SQLException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.sql.*;

public class Main {
    public static int executeSP(Connection conn, String spName, Object... parameters) throws SQLException {
        CallableStatement stmt = null;
        int result = -1;
        try {// w w  w . j  a  va2s .co m
            String sql = getCallStatementSQL(spName, parameters.length);
            stmt = conn.prepareCall(sql);
            bindParams(stmt, parameters);
            result = stmt.executeUpdate();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
        return result;
    }

    private static String getCallStatementSQL(String spName, int paramCount) {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        for (int i = 0; i < paramCount; i++) {
            sb.append("?");
            if (i < paramCount - 1) {
                sb.append(", ");
            }
        }
        sb.append(")");
        String sql = "call " + spName + sb.toString();
        return sql;
    }

    private static void bindParams(PreparedStatement stmt, Object... parameters) throws SQLException {
        for (int i = 0; i < parameters.length; i++) {
            stmt.setObject(i + 1, parameters[i]);
        }
    }

    public static int executeUpdate(Connection conn, String sql, Object... parameters) throws SQLException {
        PreparedStatement stmt = null;
        int result = -1;
        try {
            stmt = conn.prepareStatement(sql);
            bindParams(stmt, parameters);
            result = stmt.executeUpdate();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
        return result;
    }
}

Related

  1. executeInsertSQL(String sql)
  2. executeQueries(Connection conn, InputStream stream)
  3. executeResource(Connection con, String resource)
  4. executeSetArgs(PreparedStatement stmt, Object... args)
  5. executeShutDownForHSQL(java.sql.Connection connection)
  6. executeSql(Connection conn, String sql)
  7. executeSQL(Connection conn, String sql)
  8. executeSql(Connection conn, String sql)
  9. executeSQL(Connection connection, String file)