Execute an update or a delete query. - Java java.sql

Java examples for java.sql:PreparedStatement

Description

Execute an update or a delete query.

Demo Code


//package com.java2s;
import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    /**/* w  ww  .  j  a  va 2 s.  co m*/
     * Execute an update or a delete query.
     * @param conn
     * @param query
     * @throws SQLException
     */
    public static void executeUpdate(Connection conn, String query)
            throws SQLException {
        Statement st = conn.createStatement();
        st.executeUpdate(query);
        st.close();
    }

    /**
     * Execute an update or a delete query using a prepared statement.
     * @param conn
     * @param query
     * @throws SQLException
     */
    public static void executeUpdate(Connection conn, String query,
            String[] bindValues) throws SQLException {
        PreparedStatement pst = conn.prepareStatement(query);
        // porting to Java 4, to run on linux.ischool
        //for (String val : bindValues) {

        for (int i = 0; i < bindValues.length; i++) {
            String val = bindValues[i];
            pst.setString(1, val);
            pst.executeUpdate();
        }
        pst.close();
    }
}

Related Tutorials