execute Update - Java JDBC

Java examples for JDBC:SQL Statement

Description

execute Update

Demo Code


//package com.java2s;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static int executeUpdate(Connection conn, String preparedQuery,
            Object... params) {/*  ww  w  .jav a 2  s  . co m*/
        int affectedRows = 0;
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement(preparedQuery);
            fillStatement(stmt, params);
            affectedRows = stmt.executeUpdate();
        } catch (SQLException ex) {
            releaseDbConnection(conn, stmt, null);
            throw new RuntimeException(ex.getMessage(), ex);
        }
        return affectedRows;
    }

    public static void fillStatement(PreparedStatement stmt,
            Object... params) throws SQLException {
        if (params != null && params.length > 0) {
            ResultSetMetaData metadata = stmt.getMetaData();
            for (int i = 0; i < params.length; i++) {
                if (params[i] != null) {
                    stmt.setObject(i + 1, params[i]);
                } else {
                    try {
                        stmt.setNull(i + 1, metadata.getColumnType(i + 1));
                    } catch (NullPointerException ex) { // Oracle bug workaround
                        //            stmt.setNull(i + 1, java.sql.Types.VARCHAR);
                        stmt.setObject(i + 1, null);
                    }
                }
            }
        }
    }

    public static void releaseDbConnection(Connection conn, Statement stmt,
            ResultSet rset) {
        try {
            if (rset != null) {
                rset.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}

Related Tutorials