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.Jax.GenericResource.java

@DELETE
@Consumes(MediaType.APPLICATION_JSON)//from  w w w  .java2s.com
@Produces(MediaType.APPLICATION_JSON)
@Path("/delete")
public void deleteProduct(String content) throws ParseException, SQLException {

    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(content);

    Object id = json.get("id");
    String newProductID = id.toString();
    int productID = Integer.parseInt(newProductID);

    Object newName = json.get("newName");
    String name = newName.toString();

    Object newDescription = json.get("newDescription");
    String description = newDescription.toString();

    Object qty = json.get("qty");
    String newQty = qty.toString();
    int quantity = Integer.parseInt(newQty);

    Statement stmt = con.createStatement();
    String query = "DELETE FROM products WHERE productID =" + productID;
    stmt.executeUpdate(query);
}

From source file:hoot.services.models.osm.Relation.java

/**
 * Inserts a new relation into the services database with the specified ID;
 * useful for testing//  w  ww  . j  a v  a 2s .com
 *
 * @param wayId
 *          ID to assign to the new way
 * @param changesetId
 *          corresponding changeset ID for the element to be inserted
 * @param mapId
 *          corresponding map ID for the element to be inserted
 * @param members
 *          the relation's members
 * @param tags
 *          element tags
 * @param dbConn
 *          JDBC Connection
 * @throws Exception
 */
public static void insertNew(final long relId, final long changesetId, final long mapId,
        final List<RelationMember> members, final Map<String, String> tags, Connection dbConn)
        throws Exception {
    CurrentRelations relationRecord = new CurrentRelations();
    relationRecord.setChangesetId(changesetId);
    relationRecord.setId(relId);
    final Timestamp now = new Timestamp(Calendar.getInstance().getTimeInMillis());
    relationRecord.setTimestamp(now);
    relationRecord.setVersion(new Long(1));
    relationRecord.setVisible(true);
    if (tags != null && tags.size() > 0) {
        relationRecord.setTags(tags);
    }

    String strKv = "";
    if (tags != null) {
        Iterator it = tags.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            String key = "\"" + pairs.getKey() + "\"";
            String val = "\"" + pairs.getValue() + "\"";
            if (strKv.length() > 0) {
                strKv += ",";
            }

            strKv += key + "=>" + val;
        }
    }
    String strTags = "'";
    strTags += strKv;
    strTags += "'";

    String POSTGRESQL_DRIVER = "org.postgresql.Driver";
    Statement stmt = null;
    try {
        Class.forName(POSTGRESQL_DRIVER);

        stmt = dbConn.createStatement();

        String sql = "INSERT INTO current_relations_" + mapId + "(\n"
                + "            id, changeset_id, \"timestamp\", visible, version, tags)\n" + " VALUES(" + relId
                + "," + changesetId + "," + "CURRENT_TIMESTAMP" + "," + "true" + "," + "1" + "," + strTags +

                ")";
        stmt.executeUpdate(sql);
        new Relation(mapId, dbConn, relationRecord).addMembers(mapId, members);

    } catch (Exception e) {
        throw new Exception("Error inserting node.");
    }

    finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {

        } // nothing we can do

    } // end try
}

From source file:com.kylinolap.query.test.H2Database.java

private void loadH2Table(String tableName, String joinType) throws SQLException {
    MetadataManager metaMgr = MetadataManager.getInstance(config);
    TableDesc tableDesc = metaMgr.getTableDesc(tableName.toUpperCase());
    File tempFile = null;//from w  w  w  .j a  va2s. c o  m

    String fileNameSuffix = joinType.equalsIgnoreCase("default") ? "" : "." + joinType;

    try {
        tempFile = File.createTempFile("tmp_h2", ".csv");
        FileOutputStream tempFileStream = new FileOutputStream(tempFile);
        String normalPath = "/data/" + tableDesc.getName() + ".csv";

        // If it's the fact table, there will be a facttable.csv.inner or
        // facttable.csv.left in hbase
        // otherwise just use lookup.csv
        InputStream csvStream = metaMgr.getStore().getResource(normalPath + fileNameSuffix);
        if (csvStream == null) {
            csvStream = metaMgr.getStore().getResource(normalPath);
        } else {
            logger.info("H2 decides to load " + (normalPath + fileNameSuffix) + " for table "
                    + tableDesc.getName());
        }

        org.apache.commons.io.IOUtils.copy(csvStream, tempFileStream);

        csvStream.close();
        tempFileStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    // String cvsFilePath = "../examples/sample_cube/data/" +
    // tableDesc.getName() + ".csv";
    String cvsFilePath = tempFile.getPath();
    Statement stmt = h2Connection.createStatement();
    String sql = generateCreateH2TableSql(tableDesc, cvsFilePath);
    stmt.executeUpdate(sql);

    if (tempFile != null)
        tempFile.delete();
}

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

private void replayScript(File scriptFile) throws SQLException, IOException {
    if (!scriptFile.exists()) {
        return;//  w ww.  j  a va2s .  c  o m
    }

    System.out.println("Migrating hsql file: " + scriptFile.getName());
    Connection con = source.getConnection();
    Statement stmt = con.createStatement();
    stmt.executeUpdate("SET REFERENTIAL_INTEGRITY FALSE");
    LineNumberReader reader = new LineNumberReader(new FileReader(scriptFile));
    String line;
    while ((line = reader.readLine()) != null) {
        try {
            String table = null;
            Matcher matcher = createTable.matcher(line);
            if (matcher.find()) {
                table = matcher.group(2).trim();
            }

            if (line.equals("CREATE SCHEMA PUBLIC AUTHORIZATION DBA")) {
                continue;
            }
            if (line.equals("CREATE SCHEMA CRUISE AUTHORIZATION DBA")) {
                continue;
            }
            if (line.startsWith("CREATE USER SA PASSWORD")) {
                continue;
            }
            if (line.contains("BUILDEVENT VARCHAR(255)")) {
                line = line.replace("BUILDEVENT VARCHAR(255)", "BUILDEVENT LONGVARCHAR");
            }
            if (line.contains("COMMENT VARCHAR(4000)")) {
                line = line.replace("COMMENT VARCHAR(4000)", "COMMENT LONGVARCHAR");
            }
            if (line.contains("CREATE MEMORY TABLE")) {
                line = line.replace("CREATE MEMORY TABLE", "CREATE CACHED TABLE");
            }
            if (table != null && table.equals("MATERIALPROPERTIES") && line.contains("VALUE VARCHAR(255),")) {
                line = line.replace("VALUE VARCHAR(255),", "VALUE LONGVARCHAR,");
            }
            if (line.startsWith("GRANT DBA TO SA")) {
                continue;
            }
            if (line.startsWith("CONNECT USER")) {
                continue;
            }
            if (line.contains("DISCONNECT")) {
                continue;
            }
            if (line.contains("AUTOCOMMIT")) {
                continue;
            }
            stmt.executeUpdate(line);
            if (reader.getLineNumber() % LINES_PER_DOT == 0) {
                System.out.print(".");
                System.out.flush();
            }
            if (reader.getLineNumber() % (80 * LINES_PER_DOT) == 0) {
                System.out.println();
            }

        } catch (SQLException e) {
            bomb("Error executing : " + line, e);
        }
    }
    stmt.executeUpdate("SET REFERENTIAL_INTEGRITY TRUE");
    stmt.executeUpdate("CHECKPOINT SYNC");
    System.out.println("\nDone.");
    reader.close();
    stmt.close();
    con.close();
}

From source file:eu.optimis.mi.monitoring_manager.test.MonitoringManagerTest.java

private boolean deleteResources(String type) {
    DBConnection dbconn = new DBConnection();
    Connection conn = dbconn.getConnection();

    String query;//from ww w .java  2  s.  c om
    if (type.equals("physical"))
        query = "Delete FROM monitoring_resource_physical where physical_resource_id like '%UnitTest%'";
    else
        query = "Delete FROM monitoring_resource_virtual where virtual_resource_id like '%UnitTest%'";
    try {
        Statement st = conn.createStatement();
        st.executeUpdate(query);

    } catch (SQLException e) {
        logger.error("SQLException:" + e.getMessage() + ":" + e.getSQLState());
        return false;
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
    return true;
}

From source file:bizlogic.Records.java

public static void add(Connection DBcon, String sensor_name, String smpl_interval, String running, String name)
        throws SQLException {

    String isRunning;//from www .j a  va2s.c om
    Statement st;
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST WHERE NAME = '" + sensor_name + "' ");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Records.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }
    rs.next();
    int id = rs.getInt("sensor_id");

    String sql_statement;
    if (running.equals("true")) {
        isRunning = "B'1'";
    } else {
        isRunning = "B'0'";
    }

    st = DBcon.createStatement();
    sql_statement = "INSERT INTO USERCONF.LOG_LIST(SENSOR_ID, SMPL_INTERVAL, RUNNING, NAME) " + "VALUES (" + id
            + ", " + smpl_interval + ", " + isRunning + ", " + "'" + name + "'" + " );";
    System.out.println(sql_statement);
    st.clearBatch();
    st = DBcon.createStatement();
    DBcon.createStatement();
    st.executeUpdate(sql_statement);

}

From source file:com.oracle.tutorial.jdbc.ProductInformationTable.java

public void dropTable() throws SQLException {
    Statement stmt = null;
    try {/*from www.  j  a  va2 s .  co  m*/
        stmt = con.createStatement();
        if (this.dbms.equals("mysql")) {
            stmt.executeUpdate("DROP TABLE IF EXISTS PRODUCT_INFORMATION");
        } else if (this.dbms.equals("derby")) {
            stmt.executeUpdate("DROP TABLE PRODUCT_INFORMATION");
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:Employee.deleteCustomer.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w  w .jav  a 2  s .  c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try {
        String ssn = request.getParameter("ssn");
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();

        String query = "UPDATE [MatchesFromAbove].[dbo].[Customer] " + "SET Active = 0 " + "WHERE SSN = '" + ssn
                + "'";
        st.executeUpdate(query);

        //loop through result set and create the json objects

    } catch (Exception e) {
        System.out.println(e.getMessage());
        return;
    }
}

From source file:org.netxilia.spi.impl.storage.db.ddl.DDLWriter.java

/** Execute the given DDL query */
protected void executeDDLQuery(String query) throws SQLException {
    logger.info("DDLQuery: " + query);
    Connection conn = dataSource.getConnection();
    try {/*ww w  .j a v a 2 s  . c o m*/
        Statement stmt = conn.createStatement();
        stmt.executeUpdate(query);
    } finally {
        conn.close();
    }
}

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

private static void insertData(String sqlStmt) throws TorqueException, SQLException {
    Connection db = null;//from ww  w. j a  v a 2 s.c  o m
    try {
        db = Torque.getConnection(BaseTProjectTypePeer.DATABASE_NAME);
        // it's the same name for all tables here, so we don't care
        Statement stmt = db.createStatement();
        stmt.executeUpdate(sqlStmt);
    } finally {
        Torque.closeConnection(db);
    }
}