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:bizlogic.Records.java

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

    Statement st;

    String sql_statement;//  w  w  w .  ja v  a2 s  . c  om

    String _deleteRecords = deleteRecords.replace(";", ",");

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

}

From source file:com.srotya.tau.ui.Utils.java

public static void createDatabase(String dbConnectionString, String dbName, String user, String pass,
        String driver) throws Exception {
    Connection conn = null;//w  w w.  j a v  a2 s .  com
    Statement stmt = null;
    try {
        // STEP 2: Register JDBC driver
        Class.forName(driver);

        // STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(dbConnectionString, user, pass);

        // STEP 4: Execute a query
        System.out.println("Creating database...");
        stmt = conn.createStatement();

        String sql = "CREATE DATABASE IF NOT EXISTS " + dbName;
        stmt.executeUpdate(sql);
        System.out.println("Database created successfully...");
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } // end finally try
    } // end try
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public static void testCoalesce() throws SQLException {
    Statement stat = conn.createStatement();
    stat.executeUpdate("create table test(tm timestamp)");
    stat.executeUpdate("insert into test values(current_timestamp)");
    PreparedStatement prep = conn.prepareStatement("update test set tm = coalesce(?,tm)");
    prep.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
    prep.executeUpdate();/*  w  ww. ja v a2  s. com*/
    stat.executeUpdate("drop table test");
}

From source file:jfutbol.com.jfutbol.GcmSender.java

public static void updateNotificationAsSent(int userId) {
    Connection conn = null;//  w w w .ja  v  a2 s  .  c  om
    Statement stmt = null;

    try {
        // STEP 2: Register JDBC driver
        Class.forName(JDBC_DRIVER);
        // STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        // STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "UPDATE notifications SET sentByGCM=1 WHERE userId=" + userId;
        int rs = stmt.executeUpdate(sql);
        // STEP 5: Extract data from result set
        if (rs > 0) {
            // System.out.print("Notifications sent to userId: "+userId);
        }
        // STEP 6: Clean-up environment
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        // Handle errors for JDBC
        log.error(se.getMessage());
        se.printStackTrace();
    } catch (Exception e) {
        // Handle errors for Class.forName
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
            log.error(se2.getMessage());
        } // nothing we can do
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            log.error(se.getMessage());
            se.printStackTrace();
        } // end finally try
    } // end try
}

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

private static void resetSQLServer(final Connection conn) throws SQLException {

    Statement statement = conn.createStatement();
    final ResultSet resultSet = statement.executeQuery("SELECT sysobjects.name " + "FROM sysobjects "
            + "JOIN sysusers " + "ON sysobjects.uid = sysusers.uid "
            + "WHERE OBJECTPROPERTY(sysobjects.id, N'IsView') = 1");
    final List<String> drops = new ArrayList<String>();
    while (resultSet.next()) {
        drops.add("DROP VIEW " + resultSet.getString(1));
    }/*from   ww w  .jav  a 2  s .c o m*/
    resultSet.close();
    statement.close();

    statement = conn.createStatement();
    for (String drop : drops) {
        statement.executeUpdate(drop);
    }
    statement.close();

    statement = conn.createStatement();
    statement.executeUpdate("EXEC sp_MSforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"");
    statement.close();

    statement = conn.createStatement();
    statement.executeUpdate("EXEC sp_MSforeachtable \"DROP TABLE ?\"");
    statement.close();

    conn.close();
}

From source file:net.antidot.sql.model.core.SQLConnector.java

/**
 * Update a database, connected with c, with requests in SQL file.
 * /* w w w  .j av a2  s . c  om*/
 * @param c
 * @param pathToSQLFile
 * @throws SQLException
 */
public static void updateDatabase(Connection c, String pathToSQLFile) throws SQLException {
    log.debug("[SQLConnector:updateDatabase] pathToSQLFile = " + pathToSQLFile);
    StringBuilder sb = new StringBuilder();
    try {
        FileReader fr = new FileReader(new File(pathToSQLFile));
        // be sure to not have line starting with "--" or "/*" or any other
        // non aplhabetical character
        BufferedReader br = new BufferedReader(fr);

        int s = -1;
        while ((s = br.read()) != -1) {
            sb.appendCodePoint(s);
        }
        br.close();
        // here is our splitter ! We use ";" as a delimiter for each request
        // then we are sure to have well formed statements
        String[] inst = sb.toString().split(";");
        Statement st = c.createStatement();

        for (int i = 0; i < inst.length; i++) {
            // we ensure that there is no spaces before or after the request
            // string
            // in order to not execute empty statements
            if (!inst[i].trim().equals("")) {
                log.debug("[SQLConnector:updateDatabase] >> " + inst[i]);
                st.executeUpdate(inst[i]);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.ucsb.nceas.MCTestCase.java

protected static void dbUpdate(String sqlStatement, String methodName) throws SQLException {

    DBConnectionPool connPool = DBConnectionPool.getInstance();
    DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
    int serialNumber = dbconn.getCheckOutSerialNumber();

    Statement statement = dbconn.createStatement();

    debug("Executing against db: " + sqlStatement);
    statement.executeUpdate(sqlStatement);

    statement.close();/*w w  w .java 2s  . c  o m*/

    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
}

From source file:com.aurel.track.admin.customize.category.filter.PredefinedQueryBL.java

/**
 * We forgot to add also the watcher at Migrate400To410.
 * This will be added at Migrate410To412
 * Although it will not appear implicitly in the menu items for users we should define it
 * because otherwise the watcher part of MyItems dashboard does not work
 *//*from ww w.j ava2s.c  o  m*/
public static void addWatcherFilter() {
    LOGGER.info("Add watcher filters");
    FilterFacade filterFacade = FilterFacadeFactory.getInstance()
            .getFilterFacade(TQueryRepositoryBean.QUERY_PURPOSE.TREE_FILTER, true);
    // Get not closed stateIDs
    List<TStateBean> notClosedStateBeans = StatusBL.loadNotClosedStates();
    List<Integer> notClosedStateIDs = GeneralUtils.createIntegerListFromBeanList(notClosedStateBeans);
    Integer[] notClosedStatesArr = GeneralUtils.createIntegerArrFromCollection(notClosedStateIDs);
    ILabelBean watcherBean = filterFacade.getByKey(PREDEFINED_QUERY.WATCHER_ITEMS);
    if (watcherBean == null) {
        Connection cono = null;
        try {
            cono = InitDatabase.getConnection();
            Statement ostmt = cono.createStatement();
            cono.setAutoCommit(false);
            ostmt.executeUpdate(addPredefinedQueryClob(PREDEFINED_QUERY.WATCHER_ITEMS,
                    PredefinedQueryBL.getWatcherItemsExpression(notClosedStatesArr)));
            ostmt.executeUpdate(addPredefinedQuery(PREDEFINED_QUERY.WATCHER_ITEMS, "I''m watcher"));
            cono.commit();
            cono.setAutoCommit(true);
        } catch (Exception e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                if (cono != null) {
                    cono.close();
                }
            } catch (Exception e) {
                LOGGER.info("Closing the connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:model.SQLiteModel.java

public static void update(String query) {
    //query = StringEscapeUtils.escapeJavaScript(query);
    //System.out.println(query);
    Statement stmt = null;
    try {//from  ww w .ja va  2 s .  co m

        stmt = c.createStatement();
        if (stmt.executeUpdate(query) == 0) {
            writeLineToLog("Records created successfully");
        }

        stmt.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.out.println("Unsuccessful update query: " + query);
        writeLineToLog("Unsuccessful update query: " + query);
    }
}

From source file:com.srotya.tau.api.Utils.java

public static void createDatabase(String dbConnectionString, String dbName, String user, String pass,
        String driver) throws Exception {
    Connection conn = null;//from   w w  w  . j  ava2s.c  o m
    Statement stmt = null;
    try {
        // STEP 2: Register JDBC driver
        Class.forName(driver);

        // STEP 3: Open a connection
        System.out.println("Connecting to database with connection string:" + dbConnectionString);
        conn = DriverManager.getConnection(dbConnectionString, user, pass);

        // STEP 4: Execute a query
        System.out.println("Creating database...");
        stmt = conn.createStatement();

        String sql = "CREATE DATABASE IF NOT EXISTS " + dbName;
        stmt.executeUpdate(sql);
        System.out.println("Database created successfully...");
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } // end finally try
    } // end try
}