Java SQL Execute executeInsert(Connection conn, String sql, boolean hasAutoGeneratedKey, Object... parameters)

Here you can find the source of executeInsert(Connection conn, String sql, boolean hasAutoGeneratedKey, Object... parameters)

Description

execute Insert

License

Apache License

Declaration

public static long executeInsert(Connection conn, String sql, boolean hasAutoGeneratedKey, Object... parameters)
            throws SQLException 

Method Source Code

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

import java.sql.*;

public class Main {
    public static long executeInsert(Connection conn, String sql, boolean hasAutoGeneratedKey, Object... parameters)
            throws SQLException {
        PreparedStatement stmt = null;
        ResultSet generatedKeysResultSet = null;
        long result = -1;
        try {//from www .ja v a 2 s  .  c  o m
            if (hasAutoGeneratedKey) {
                stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            } else {
                stmt = conn.prepareStatement(sql);
            }
            bindParams(stmt, parameters);
            stmt.executeUpdate();
            if (hasAutoGeneratedKey) {
                generatedKeysResultSet = stmt.getGeneratedKeys();
                if (generatedKeysResultSet.next()) {
                    result = generatedKeysResultSet.getLong(1);
                }
            }
        } finally {
            if (generatedKeysResultSet != null) {
                generatedKeysResultSet.close();
            }

            if (stmt != null) {
                stmt.close();
            }
        }
        return result;
    }

    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. executeCallable(Connection conn, String sql)
  2. executeCreateDB(String className, String URL, String userName, String password, String dbName)
  3. executeDDL(final Connection connection, final String sql, final int... ignoreErrors)
  4. executeDDL(String ddl)
  5. executeImmediate(String sql)
  6. executeInsert(Connection conn, String targetTable, String destinationTable)
  7. executeInsertSQL(String sql)
  8. executeQueries(Connection conn, InputStream stream)
  9. executeResource(Connection con, String resource)