Example usage for java.sql Statement executeUpdate

List of usage examples for java.sql Statement executeUpdate

Introduction

In this page you can find the example usage for java.sql Statement executeUpdate.

Prototype

int executeUpdate(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

Usage

From source file:hnu.helper.DataBaseConnection.java

/**
 * Create and Execute an SQL PreparedStatement and returns true if
 * everything went ok. Can be used for DML and DDL.
 * Borrows from apache.commons.scaffold.sql.StatementUtils (see
 * jakarta-commons-sandbox/scaffold)/*from ww  w.  j a  v a2 s. c o m*/
 */
public static boolean execute(String sql, Object[] parameters) {
    DataBaseConnection db = new DataBaseConnection();
    boolean returnValue = false;
    Connection conn = db.getDBConnection();
    PreparedStatement pStmt = null;
    Statement stmt = null;

    log.debug("About to execute: " + sql);
    try {
        if (parameters == null || (parameters.length == 0)) {
            stmt = conn.createStatement();
            stmt.executeUpdate(sql);
        } else {
            pStmt = conn.prepareStatement(sql);
            for (int i = 0; i < parameters.length; i++) {
                log.debug("parameter " + i + ": " + parameters[i]);
                pStmt.setObject(i + 1, parameters[i]);
            }
            pStmt.executeUpdate();
        }
        log.debug(".. executed without exception (hope to return 'true') ");
        returnValue = true;
    } catch (SQLException ex) {
        log.error("Error executing: '" + sql + "'", ex);
        returnValue = false;
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (pStmt != null) {
                pStmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
            log.error("Couldn't close the statement or connection.", ex);
        }
    }
    return returnValue;
}

From source file:Main.java

public static void UpdateTable1(Statement stmt, String package_name, String app_name, String decode_app,
        String has_sdk, String has_sdk_pro, String app_version, String app_url, String app_icon) {
    String sql = "UPDATE app_info.`pack_only_copy_8.12_copy` SET package_name='" + package_name
            + "',decode_app='" + decode_app + "',has_sdk='" + has_sdk + "',has_sdk_pro='" + has_sdk_pro
            + "',app_version='" + app_version + "',app_url='" + app_url + "',app_icon='" + app_icon + "'\n"
            + "WHERE app_name='" + app_name + "'";
    try {//ww w .j av  a 2  s .  c  om
        stmt.executeUpdate(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:com.baidu.qa.service.test.util.JdbcUtil.java

protected static int excuteInsertOrUpdateSql(String sql, String dbname) throws Exception {

    //   ???//from  ww w.java 2s. com
    Connection con = null;
    Statement sm = null;
    try {
        con = MysqlDatabaseManager.getCon(dbname);
        Assert.assertNotNull("connect to db error:" + dbname, con);
        //??
        sm = con.createStatement();
        log.info("[sql:]" + sql);
        return sm.executeUpdate(sql);

    } catch (Exception e) {
        throw e;
    } finally {
        if (con != null) {
            con.close();

        }
        if (sm != null) {
            sm.close();
        }

    }

}

From source file:bizlogic.Sensors.java

public static void del(Connection DBcon, String deleteSensors) throws SQLException {

    Statement st = null;
    ResultSet rs = null;/*w ww  .  j a  v  a2s .com*/

    String sql_statement;

    String _deleteSensors = deleteSensors.replace(";", ",");

    st = DBcon.createStatement();
    //for(int i = 0; i<30; i++) {
    sql_statement = "DELETE FROM USERCONF.SENSORLIST WHERE SENSOR_ID IN(" + _deleteSensors + ")";
    System.out.println(sql_statement);
    st.clearBatch();
    st = DBcon.createStatement();
    DBcon.createStatement();
    st.executeUpdate(sql_statement);

}

From source file:com.micromux.cassandra.jdbc.CollectionsTest.java

/**
 * @throws java.lang.Exception/*from w  w w  .  j  a v  a  2 s  .com*/
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    // configure OPTIONS
    if (!StringUtils.isEmpty(TRUST_STORE)) {
        OPTIONS = String.format("trustStore=%s&trustPass=%s", URLEncoder.encode(TRUST_STORE), TRUST_PASS);
    }

    Class.forName("com.micromux.cassandra.jdbc.CassandraDriver");
    String URL = String.format("jdbc:cassandra://%s:%d/%s?%s&version=%s", HOST, PORT, SYSTEM, OPTIONS, CQLV3);

    con = DriverManager.getConnection(URL);

    if (LOG.isDebugEnabled())
        LOG.debug("URL         = '{}'", URL);

    Statement stmt = con.createStatement();

    // Use Keyspace
    String useKS = String.format("USE %s;", KEYSPACE);

    // Drop Keyspace
    String dropKS = String.format("DROP KEYSPACE %s;", KEYSPACE);

    try {
        stmt.execute(dropKS);
    } catch (Exception e) {
        /* Exception on DROP is OK */}

    // Create KeySpace
    String createKS = String.format(
            "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy',  'replication_factor' : 1  };",
            KEYSPACE);
    //        String createKS = String.format("CREATE KEYSPACE %s WITH strategy_class = SimpleStrategy AND strategy_options:replication_factor = 1;",KEYSPACE);
    if (LOG.isDebugEnabled())
        LOG.debug("createKS    = '{}'", createKS);

    stmt = con.createStatement();
    stmt.execute("USE " + SYSTEM);
    stmt.execute(createKS);
    stmt.execute(useKS);

    // Create the target Table (CF)
    String createTable = "CREATE TABLE testcollection (" + " k int PRIMARY KEY," + " L list<bigint>,"
            + " M map<double, boolean>, M2 map<text, timestamp>, S set<text>" + ") ;";
    if (LOG.isDebugEnabled())
        LOG.debug("createTable = '{}'", createTable);

    stmt.execute(createTable);
    stmt.close();
    con.close();

    // open it up again to see the new TABLE
    URL = String.format("jdbc:cassandra://%s:%d/%s?%s&version=%s", HOST, PORT, KEYSPACE, OPTIONS, CQLV3);
    con = DriverManager.getConnection(URL);
    if (LOG.isDebugEnabled())
        LOG.debug("URL         = '{}'", URL);

    Statement statement = con.createStatement();

    String insert = "INSERT INTO testcollection (k,L) VALUES( 1,[1, 3, 12345]);";
    statement.executeUpdate(insert);
    String update1 = "UPDATE testcollection SET S = {'red', 'white', 'blue'} WHERE k = 1;";
    String update2 = "UPDATE testcollection SET M = {2.0: true, 4.0: false, 6.0 : true} WHERE k = 1;";
    statement.executeUpdate(update1);
    statement.executeUpdate(update2);

    if (LOG.isDebugEnabled())
        LOG.debug("Unit Test: 'CollectionsTest' initialization complete.\n\n");
}

From source file:Main.java

public static void UpdateTable2(Statement stmt, String package_name, String app_name, String app_versioncode,
        String decode_app, String has_sdk, String msp_version, String msp_pro, String app_url,
        String app_icon) {/* w  w w.j a v  a 2 s .c  om*/
    String sql = "UPDATE app_info.`msp_table_8.12_copy` SET package_name='" + package_name
            + "',app_versioncode='" + app_versioncode + "',decode_app='" + decode_app + "',has_sdk='" + has_sdk
            + "',msp_version='" + msp_version + "',msp_pro='" + msp_pro + "',app_url='" + app_url
            + "',app_icon='" + app_icon + "'\n" + "WHERE app_name='" + app_name + "'";
    try {
        stmt.executeUpdate(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:net.tirasa.ilgrosso.resetdb.Main.java

private static void resetOracle(final Connection conn) throws Exception {

    final Statement statement = conn.createStatement();

    ResultSet resultSet = statement.executeQuery(
            "SELECT 'DROP VIEW ' || object_name || ';'" + " FROM user_objects WHERE object_type='VIEW'");
    final List<String> drops = new ArrayList<String>();
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }//from ww  w.  j a va  2 s  .c  o  m
    resultSet.close();

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }
    drops.clear();

    resultSet = statement.executeQuery("SELECT 'DROP INDEX ' || object_name || ';'"
            + " FROM user_objects WHERE object_type='INDEX'" + " AND object_name NOT LIKE 'SYS_%'");
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }
    resultSet.close();

    for (String drop : drops) {
        try {
            statement.executeUpdate(drop.substring(0, drop.length() - 1));
        } catch (SQLException e) {
            LOG.error("Could not perform: {}", drop);
        }
    }
    drops.clear();

    resultSet = statement.executeQuery("SELECT 'DROP TABLE ' || table_name || ' CASCADE CONSTRAINTS;'"
            + " FROM all_TABLES WHERE owner='" + ((String) ctx.getBean("username")).toUpperCase() + "'");
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }
    resultSet.close();

    resultSet = statement
            .executeQuery("SELECT 'DROP SEQUENCE ' || sequence_name || ';'" + " FROM user_SEQUENCES");
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }
    resultSet.close();

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }

    statement.close();
    conn.close();
}

From source file:gridool.util.jdbc.JDBCUtils.java

/**
 * Execute an SQL INSERT, UPDATE, or DELETE query without replacement
 * parameters.//from  w  ww.ja va 2s.  c  o  m
 * 
 * @param conn The connection to use to run the query.
 * @param sql The SQL to execute.
 * @return The number of rows updated.
 */
public static int update(Connection conn, String sql) throws SQLException {
    Statement stmt = null;
    int rows = 0;
    try {
        stmt = conn.createStatement();
        verboseQuery(sql, (Object[]) null);
        rows = stmt.executeUpdate(sql);
    } catch (SQLException e) {
        rethrow(e, sql, (Object[]) null);
    } finally {
        close(stmt);
    }
    return rows;
}

From source file:net.tirasa.ilgrosso.resetdb.Main.java

private static void resetMySQL(final Connection conn) throws Exception {

    final Statement statement = conn.createStatement();

    ResultSet resultSet = statement
            .executeQuery("SELECT concat('DROP VIEW IF EXISTS ', table_name, ' CASCADE;')"
                    + "FROM information_schema.views;");
    final List<String> drops = new ArrayList<String>();
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }//from www .j  a  v  a  2 s  . c  o m
    resultSet.close();

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }
    drops.clear();

    drops.add("SET FOREIGN_KEY_CHECKS = 0;");
    resultSet = statement.executeQuery("SELECT concat('DROP TABLE IF EXISTS ', table_name, ' CASCADE;')"
            + "FROM information_schema.tables;");
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }
    resultSet.close();
    drops.add("SET FOREIGN_KEY_CHECKS = 1;");

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }

    statement.close();
    conn.close();
}

From source file:org.easyrec.utils.Benchmark.java

private static void createIdMapping(Statement st) throws Exception {
    for (int i = 1; i <= Math.max(NUMBER_OF_ITEMS, NUMBER_OF_USERS); i++) {

        StringBuilder s = new StringBuilder().append("          INSERT INTO ").append("  idmapping").append("(")
                .append("  intId,").append("  stringId").append(") ").append("VALUE (").append(i).append("  ,")
                .append(i).append(")");
        st.executeUpdate(s.toString());//from  ww w . j  a va 2  s  .c  om
    }
    System.out.println("idmapping created.");
}