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:com.google.gerrit.server.schema.H2AccountPatchReviewStore.java

private static void doCreateTable(Statement stmt) throws SQLException {
    stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ACCOUNT_PATCH_REVIEWS ("
            + "ACCOUNT_ID INTEGER DEFAULT 0 NOT NULL, " + "CHANGE_ID INTEGER DEFAULT 0 NOT NULL, "
            + "PATCH_SET_ID INTEGER DEFAULT 0 NOT NULL, " + "FILE_NAME VARCHAR(255) DEFAULT '' NOT NULL, "
            + "CONSTRAINT PRIMARY_KEY_ACCOUNT_PATCH_REVIEWS "
            + "PRIMARY KEY (ACCOUNT_ID, CHANGE_ID, PATCH_SET_ID, FILE_NAME)" + ")");
}

From source file:com.thoughtworks.go.server.database.DatabaseFixture.java

public static int update(String query, H2Database h2Database) {
    BasicDataSource source = h2Database.createDataSource();
    Connection con = null;/*w w w  . j  av a  2 s.co  m*/
    Statement stmt = null;
    try {
        con = source.getConnection();
        stmt = con.createStatement();
        return stmt.executeUpdate(query);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            assert stmt != null;
            stmt.close();
            con.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.example.mydtapp.JdbcInputAppTest.java

@BeforeClass
public static void setup() {
    try {/*from   w  w  w  .ja  v  a2  s . c o  m*/
        cleanup();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    try {
        Class.forName(DB_DRIVER).newInstance();

        Connection con = DriverManager.getConnection(URL);
        Statement stmt = con.createStatement();

        String createTable = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
                + " (ACCOUNT_NO INTEGER, NAME VARCHAR(255),AMOUNT INTEGER)";
        stmt.executeUpdate(createTable);
        cleanTable();
        insertEventsInTable(10, 0);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * //from w ww  . j av a2s. co  m
 * @param conn
 * @param table
 * @param c_name
 */
public static void updateContentVersion(Connection conn, String table, String c_name) throws Exception {
    ResultSet rs;
    Statement s;
    int v;

    s = conn.createStatement();
    rs = s.executeQuery("SELECT c_version FROM " + table + " WHERE c_name = '" + c_name + "'");
    v = 1;

    if (rs.next()) {
        v = rs.getInt(1);
        v++;
    }

    rs.close();

    s.executeUpdate("UPDATE " + table + " SET c_version = " + v + " WHERE c_name = '" + c_name + "'");
    s.close();
}

From source file:com.aurel.track.dbase.Migrate416To417.java

/**
 * Add the document and document section
 * Use JDBC because negative objectIDs should be added
 *///w  w  w.j  a  va  2s  .  c o  m
public static void addDeletedBasket() {
    TBasketBean basketBean = BasketBL.getBasketByID(TBasketBean.BASKET_TYPES.DELETED);
    if (basketBean == null) {
        LOGGER.info("Add 'Deleted basket' basket");
        Connection cono = null;
        try {
            cono = InitDatabase.getConnection();
            Statement ostmt = cono.createStatement();
            cono.setAutoCommit(false);
            String deletedBasketStmt = addDeletedBasketStmt(TBasketBean.BASKET_TYPES.DELETED, "basket.label.-1",
                    "-1001");
            ostmt.executeUpdate(deletedBasketStmt);
            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:com.cloudera.sqoop.manager.OracleUtils.java

/**
 * Drop a table if it exists.//from   www .j a  va 2s . c om
 */
public static void dropTable(String tableName, ConnManager manager) throws SQLException {
    Connection connection = null;
    Statement st = null;

    try {
        connection = manager.getConnection();
        connection.setAutoCommit(false);
        st = connection.createStatement();

        // create the database table and populate it with data.
        st.executeUpdate(getDropTableStatement(tableName));

        connection.commit();
    } finally {
        try {
            if (null != st) {
                st.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("Got SQLException when closing connection: " + sqlE);
        }
    }
}

From source file:io.undertow.js.test.jdbc.JavascriptJDBCWrapperTestCase.java

@BeforeClass
public static void setup() throws Exception {
    ds = JdbcConnectionPool.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "user", "password");

    Connection conn = null;//w w w.  j a v a2  s  .  c o  m
    Statement statement = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(true);
        statement = conn.createStatement();
        statement.executeUpdate("CREATE TABLE PUBLIC.CUSTOMER (" + " id SERIAL NOT NULL,"
                + " first VARCHAR(255) NOT NULL," + " last VARCHAR(255)," + " PRIMARY KEY (id)" + " );");
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (conn != null) {
            conn.close();
        }

    }

    js = UndertowJS.builder().addInjectionProvider(new TestDatabaseInjection())
            .addResources(new ClassPathResourceManager(JavascriptJDBCWrapperTestCase.class.getClassLoader(),
                    JavascriptJDBCWrapperTestCase.class.getPackage()), "jdbc.js")
            .build();
    js.start();
    DefaultServer.setRootHandler(js.getHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send("Default Response");
        }
    }));
}

From source file:com.aurel.track.dbase.Migrate411To412.java

/**
 * Add the document and document section
 * Use JDBC because negative objectIDs should be added
 *///from  www. j  a  v  a2  s  . c o m
public static void addNewItemTypes() {
    LOGGER.info("Add new item types");
    List<String> itemTypeStms = new ArrayList<String>();
    TListTypeBean docIssueTypeBean = IssueTypeBL.loadByPrimaryKey(-4);
    if (docIssueTypeBean == null) {
        LOGGER.info("Add 'Document' item type");
        itemTypeStms.add(addItemtype(-4, "Document", 4, -4, "document.png", "2007"));
    }
    TListTypeBean docSectionIssueTypeBean = IssueTypeBL.loadByPrimaryKey(-5);
    if (docSectionIssueTypeBean == null) {
        LOGGER.info("Add 'Document section' item type");
        itemTypeStms.add(addItemtype(-5, "Document section", 5, -5, "documentSection.png", "2008"));
    }
    Connection cono = null;
    try {
        cono = InitDatabase.getConnection();
        Statement ostmt = cono.createStatement();
        cono.setAutoCommit(false);
        for (String filterClobStmt : itemTypeStms) {
            ostmt.executeUpdate(filterClobStmt);
        }
        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));
        }
    }
    //children types
    List<TChildIssueTypeBean> childIssueTypeBeans = ChildIssueTypeAssignmentsBL
            .loadByChildAssignmentsByParent(-4);
    if (childIssueTypeBeans == null || childIssueTypeBeans.isEmpty()) {
        //document may have only document section children
        ChildIssueTypeAssignmentsBL.save(-4, -5);
    }
    TListTypeBean actionItemIssueTypeBean = IssueTypeBL.loadByPrimaryKey(5);
    TListTypeBean meetingIssueTypeBean = IssueTypeBL.loadByPrimaryKey(-3);
    if (actionItemIssueTypeBean != null && meetingIssueTypeBean != null) {
        //action item exists
        childIssueTypeBeans = ChildIssueTypeAssignmentsBL.loadByChildAssignmentsByParent(-3);
        if (childIssueTypeBeans == null || childIssueTypeBeans.isEmpty()) {
            //meeting may have only action item children
            ChildIssueTypeAssignmentsBL.save(-3, 5);
        }
    }
}

From source file:chat.Models.java

/** @param test whether use the testing database */
public static AnnotationConfiguration build(boolean test) throws Exception {
    AnnotationConfiguration conf = new AnnotationConfiguration() {
        private static final long serialVersionUID = 1L;

        @Override//from  www .  ja v  a  2s  .c  o  m
        public SessionFactory buildSessionFactory() throws HibernateException {
            if (!"org.hsqldb.jdbcDriver".equals(getProperty(Environment.DRIVER)))
                return super.buildSessionFactory();
            // fix the issue of hsqldb write delay stupid default value
            SessionFactory fac = super.buildSessionFactory();
            try {
                SessionImpl hib = (SessionImpl) fac.openSession();
                hib.beginTransaction();
                Statement stat = hib.getJDBCContext().borrowConnection().createStatement();
                stat.executeUpdate("SET WRITE_DELAY FALSE");
                hib.getTransaction().commit();
                stat.close();
                hib.close();
                LOG.info("SET WRITE_DELAY FALSE");
            } catch (Exception e) {
                throw new Error(e);
            }
            return fac;
        }
    };
    InputStreamReader connect = new InputStreamReader(
            Models.class.getResourceAsStream("/hibernate.connect.properties"), "UTF-8");
    conf.getProperties().load(connect);
    connect.close();

    conf.setNamingStrategy(new NamingStrategy() {
        @Override
        public String classToTableName(String entity) {
            return StringHelper.unqualify(entity);
        }

        @Override
        public String propertyToColumnName(String property) {
            return StringHelper.unqualify(property);
        }

        @Override
        public String tableName(String table) {
            return table;
        }

        @Override
        public String columnName(String column) {
            return column;
        }

        @Override
        public String collectionTableName(String ownerEntity, String ownerTable, String associatedEntity,
                String associatedTable, String property) {
            return ownerTable + "_" + StringHelper.unqualify(property);
        }

        @Override
        public String joinKeyColumnName(String joinedColumn, String joinedTable) {
            return joinedColumn;
        }

        @Override
        public String foreignKeyColumnName(String property, String propertyEntity, String propertyTable,
                String referencedColumn) {
            return property != null ? StringHelper.unqualify(property) : propertyTable;
        }

        @Override
        public String logicalColumnName(String column, String property) {
            return StringHelper.isEmpty(column) ? StringHelper.unqualify(property) : column;
        }

        @Override
        public String logicalCollectionTableName(String table, String ownerTable, String associatedTable,
                String property) {
            if (table != null)
                return table;
            return ownerTable + "_" + StringHelper.unqualify(property);
        }

        @Override
        public String logicalCollectionColumnName(String column, String property, String referencedColumn) {
            return StringHelper.isEmpty(column) ? property + "_" + referencedColumn : column;
        }
    });

    for (Class<?> c : Class2.packageClasses(Id.class))
        conf.addAnnotatedClass(c);

    if (!"false".equals(conf.getProperty(Environment.AUTOCOMMIT)))
        throw new RuntimeException(Environment.AUTOCOMMIT + " must be false");
    if (test)
        conf.setProperty(Environment.URL, conf.getProperty(Environment.URL + ".test"));
    return conf;
}

From source file:net.ontopia.topicmaps.db2tm.ChangelogTestCase.java

private static void importCSV(Statement stm, String table, String file, boolean load_data)
        throws IOException, SQLException {
    // first, get rid of the table if it's already there
    try {//w w w. j  a  v  a2  s . com
        stm.executeUpdate("drop table " + table);
    } catch (SQLException e) {
        // table wasn't there. never mind
    }

    // open the CSV file
    String csv = TestFileUtils.getTransferredTestInputFile(testdataDirectory, "in", "sync", file).getPath();
    FileReader reader = new FileReader(csv);
    CSVReader csvreader = new CSVReader(reader, ';', '"');

    // read the first line to get the column names
    String[] colnames = csvreader.readNext();
    String[] columndefs = new String[colnames.length];
    for (int ix = 0; ix < colnames.length; ix++)
        columndefs[ix] = colnames[ix] + " varchar";

    // now we can create the table
    stm.executeUpdate("create table " + table + " (" + StringUtils.join(columndefs, ", ") + ")");

    // are we just creating the table, or should we load the data?
    if (!load_data)
        return;

    // ok, now insert the actual data
    String cols = StringUtils.join(colnames, ", ");
    String[] tuple = csvreader.readNext();
    while (tuple != null) {
        String[] values = new String[tuple.length];
        for (int ix = 0; ix < tuple.length; ix++)
            values[ix] = "'" + tuple[ix] + "'"; // escaping? hah!

        stm.executeUpdate(
                "insert into " + table + " (" + cols + ") values (" + StringUtils.join(values, ", ") + ")");

        tuple = csvreader.readNext();
    }
}