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.chargebee.JDBC.PhoneBook.Phnbk.java

private void createTables(Statement statement) throws SQLException {

    String crtTabl = "CREATE TABLE phone_book " + "(id INTEGER NOT NULL AUTO_INCREMENT, "
            + " name VARCHAR(255), " + " address VARCHAR(255), " + " PRIMARY KEY ( id ))";

    statement.executeUpdate(crtTabl);

    crtTabl = "CREATE TABLE mobile_number " + "(id INT(11), " + " number INT(11), "
            + " PRIMARY KEY ( number ))";

    statement.executeUpdate(crtTabl);//from   w  w w.j a  v a2 s.  co  m

    crtTabl = "CREATE TABLE home_number " + "(id INT(11), " + " number INT(11), " + " PRIMARY KEY ( number ))";

    statement.executeUpdate(crtTabl);

    crtTabl = "CREATE TABLE work_number " + "(id INT(11), " + " number INT(11), " + " PRIMARY KEY ( number ))";

    statement.executeUpdate(crtTabl);

}

From source file:dao.RuleDao.java

/**
 * Deletes a rule from a target DB and from the local APEX db
 * /*from w  ww  . j  av  a2s  .com*/
 * @param id
 * @return
 * @throws Exception
 */
public boolean deleteRule(int id) throws Exception {
    int brgId = 0;
    String name = "";
    PreparedStatement statement = this.getApexConnection()
            .prepareStatement("SELECT BRG_PROJECTID, NAME FROM BUSINESSRULE WHERE ID=?");
    statement.setInt(1, id);
    ResultSet result = statement.executeQuery();
    while (result.next()) {
        brgId = result.getInt("BRG_PROJECTID");
        name = result.getString("NAME");
    }
    statement.close();
    Statement statementTarget = null;

    try {
        Project project = this.getProject(brgId);
        statementTarget = this.getTargetConnection(project.getTargetConfig()).createStatement();
        statementTarget.executeUpdate("DROP TRIGGER " + name.toUpperCase());
        statementTarget.close();
    } catch (Exception e) {
        Logger log = new Logger();
        log.out(Level.ERROR, "deleteRule", "Rule or project doesn't excist");
    }

    Statement statementRemoveApex = this.getApexConnection().createStatement();
    statementRemoveApex.addBatch("DELETE FROM RULE_COLUMN WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM RULE_TABLE WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM RULE_VALUE WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM BUSINESSRULE WHERE ID=" + id);
    statementRemoveApex.executeBatch();
    statementRemoveApex.close();

    return true;
}

From source file:com.jjtree.servelet.Accounts.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w ww. j  av  a  2s .co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    JSONObject jsonObject = JConverter.convert(request);
    if (jsonObject == null) {
        return;
    }

    String account = null;
    String password = null;
    String name = null;
    try {
        account = jsonObject.getString("account");
        name = jsonObject.getString("name");
        password = jsonObject.getString("password");

        if (account == null || password == null || name == null) {
            return;
        }
    } catch (JSONException ex) {
        Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {

        // Register JDBC driver
        Class.forName(JConstant.JDBC_DRIVER);

        // Open a connection
        conn = DriverManager.getConnection(JConstant.DB_URL, JConstant.USER, JConstant.PASSWORD);

        // Execute SQL query
        stmt = conn.createStatement();

        String sql = "SELECT MAX(userID) FROM JUser";
        ResultSet rs = stmt.executeQuery(sql);

        int nextUserID = 0;
        // Extract data from result set
        while (rs.next()) {
            nextUserID = rs.getInt(1) + 1;
        }

        String insertSql = null;
        if (JString.isEmail(account)) {
            insertSql = "INSERT INTO JUser(email, password, name, userID) VALUES ('" + account + "', '"
                    + password + "', '" + name + "', " + nextUserID + ")";
        }

        if (JString.isPhoneNumber(account)) {
            insertSql = "INSERT INTO JUser(mobile, password, name, userID) VALUES ('" + account + "', '"
                    + password + "', '" + name + "', " + nextUserID + ")";
        }

        Statement stmt2 = conn.createStatement();
        stmt2.executeUpdate(insertSql);

        String accountUrl = "/accounts/" + nextUserID;

        JSONObject accountObject = JServeletManager.fetchFrom(request, accountUrl);

        PrintWriter writer = response.getWriter();
        writer.print(accountObject);
        writer.flush();

        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } 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:net.ontopia.persistence.rdbms.CSVImport.java

public void importCSV(InputStream csvfile) throws Exception {
    // Execute statements
    try {//from   w ww  .jav  a2  s . c  om

        String[] qmarks = new String[columns.length];
        for (int i = 0; i < qmarks.length; i++) {
            qmarks[i] = "?";
        }

        if (cleartable) {
            String delsql = "delete from " + table;
            Statement delstm = conn.createStatement();
            delstm.executeUpdate(delsql);
            //! conn.commit();
        }

        String sql = "insert into " + table + " (" + StringUtils.join(columns, ", ") + ") values ("
                + StringUtils.join(qmarks, ", ") + ")";
        log.debug("SQL: " + sql);
        PreparedStatement stm = conn.prepareStatement(sql);

        int datatypes[] = new int[columns.length];
        for (int i = 0; i < columns.length; i++) {
            Table tbl = project.getTableByName(table);
            if (tbl == null)
                throw new OntopiaRuntimeException("Unknown table: " + table);
            Column col = tbl.getColumnByName(columns[i]);
            if (col == null)
                throw new OntopiaRuntimeException("Unknown table column: " + columns[i]);
            if (col.getType() == null)
                throw new OntopiaRuntimeException("Column type is null: " + col.getType());
            DataType datatype = project.getDataTypeByName(col.getType(), "generic");
            if (datatype == null)
                throw new OntopiaRuntimeException("Unknown column type: " + col.getType());
            String dtype = datatype.getType();
            if ("varchar".equals(dtype))
                datatypes[i] = Types.VARCHAR;
            else if ("integer".equals(dtype))
                datatypes[i] = Types.INTEGER;
            else
                throw new OntopiaRuntimeException("Unknown datatype: " + dtype);
        }

        LineNumberReader reader = new LineNumberReader(new InputStreamReader(csvfile));

        // Ignore first X lines
        for (int i = 0; i < ignorelines; i++) {
            String line = reader.readLine();
            if (line == null)
                break;
        }

        // Process input
        log.debug("[" + StringUtils.join(columns, ", ") + "]");
        int lineno = 0;
        while (true) {
            lineno++;
            String line = reader.readLine();
            if (line == null)
                break;
            try {
                String[] cols = StringUtils.split(line, separator);
                if (cols.length > columns.length && !ignorecolumns)
                    log.debug("Ignoring columns: " + (columns.length + 1) + "-" + cols.length + " '" + line
                            + "'");
                log.debug("CVALUES: " + (columns.length + 1) + "-" + cols.length + " '" + line + "'");

                String dmesg = "(";
                for (int i = 0; i < columns.length; i++) {
                    String col = cols[i];
                    // If first column character is '"' strip quotes.
                    if (stripquotes) {
                        int len = col.length();
                        if (len > 1 && ((col.charAt(0) == '"' && col.charAt(len - 1) == '"')
                                || (col.charAt(0) == '\'' && col.charAt(len - 1) == '\'')))
                            col = col.substring(1, len - 1);
                    }
                    if (col != null && col.equals(""))
                        col = null;

                    dmesg = dmesg + col;
                    if (i < columns.length - 1)
                        dmesg = dmesg + ", ";
                    stm.setObject(i + 1, col, datatypes[i]);
                }
                dmesg = dmesg + ")";
                log.debug(dmesg);
                stm.execute();
            } catch (Exception e) {
                conn.rollback();
                throw new OntopiaRuntimeException("Cannot read line " + lineno + ": '" + line + "'", e);
            }
        }
        conn.commit();
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:com.agileapes.webexport.io.impl.DatabaseOutputManager.java

@Override
public void commit(DatabaseAddress address, DatabaseContent content) throws IOException {
    final Connection connection = getConnection(address);

    final Statement statement;
    try {/*  w w  w . ja  va  2  s .c  o m*/
        statement = connection.createStatement();
    } catch (SQLException e) {
        throw new IOException("Failed to create statement", e);
    }
    try {
        statement.executeUpdate(content.getStatement());
    } catch (SQLException e) {
        throw new IOException("Failed to execute given statement", e);
    }
}

From source file:com.l2jfree.gameserver.idfactory.IdFactory.java

/**
 * Sets all character offline/*  w ww. j  a  va  2  s  .  c  om*/
 */
protected void setAllCharacterOffline() {
    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        Statement s2 = con.createStatement();
        s2.executeUpdate("UPDATE characters SET online = 0;");
        if (_log.isDebugEnabled())
            _log.debug("Updated characters online status.");
        s2.close();
    } catch (SQLException e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.silverpeas.wysiwyg.dynamicvalue.AbstractBaseDynamicValue.java

/**
 * @throws java.lang.Exception/*from   w  w  w  .j av  a  2 s  .c  om*/
 */
@After
@Override
public void tearDown() throws Exception {
    Connection con = null;
    Statement statement = null;
    try {
        // delete the table created in the setup.
        con = getConnection().getConnection();
        statement = con.createStatement();
        String sql = "DROP TABLE val_dyn1";
        statement.executeUpdate(sql);
    } finally {
        DBUtil.close(statement);
        DBUtil.close(con);
    }
}

From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java

private void parseReq(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   ww w  .j a va 2  s .  c  o  m

        MF mf = MF.getFactory();

        req.setCharacterEncoding("UTF-8");

        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(req);

        HashMap<String, String> map = new HashMap<String, String>();

        while (iterator.hasNext()) {

            FileItemStream item = iterator.next();

            InputStream stream = item.openStream();

            if (item.isFormField()) {

                String field = item.getFieldName();

                String value = Streams.asString(stream);

                map.put(field, value);

                stream.close();

            } else {

                String filename = item.getName();

                String[] extension = filename.split("\\.");

                String mail = map.get("mail");

                if (mail != null) {

                    filename = mail + "_" + String.valueOf(filename.hashCode()) + "."
                            + extension[extension.length - 1];

                } else {

                    filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1];

                }

                map.put("filename", filename);

                byte[] buffer = IOUtils.toByteArray(stream);

                mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer,

                        filename);

                stream.close();

            }

        }

        String email = map.get("mail");

        String firstName = map.get("firstName");

        String lastName = map.get("lastName");

        String dayS = map.get("day");

        String monthS = map.get("month");

        String yearS = map.get("year");

        String password = map.get("password");

        String filename = map.get("filename");

        String date = yearS + "-" + monthS + "-" + dayS;

        char gender = map.get("gender").charAt(0);

        RequestDispatcher disp;

        Connection c = mf.getSQLService().getConnection();

        String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName
                + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')";

        Statement statement = c.createStatement();

        statement.executeUpdate(stm);

        statement.close();

        c.close();

        req.getSession(true).setAttribute("actualUser", email);

        req.getSession(true).setAttribute("edit", "false");

        disp = req.getRequestDispatcher("SelectTopic.jsp");

        disp.forward(req, response);

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    } catch (SQLException e) {

        e.printStackTrace();

    } catch (FileUploadException e) {

        e.printStackTrace();

    }

}

From source file:com.aerothai.database.devicetype.DeviceTypeService.java

/**
* Method to check whether uname and pwd combination are correct
* 
* @param uname//w w  w. j ava  2 s. co m
* @param pwd
* @return
* @throws Exception
*/
public String updateDeviceType(String query) throws Exception {

    Connection dbConn = null;
    JSONObject obj = new JSONObject();

    try {
        dbConn = DBConnection.createConnection();

        Statement stmt = dbConn.createStatement();
        System.out.println(query);
        stmt.executeUpdate(query);

        obj.put("tag", "update");
        obj.put("msg", "done");
        obj.put("status", true);

    } catch (SQLException sqle) {
        throw sqle;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return obj.toJSONString();
}

From source file:com.aerothai.database.devicetype.DeviceTypeService.java

/**
 * Method to check whether uname and pwd combination are correct
 * //from  ww  w.j a  v a2  s  .  co m
 * @param uname
 * @param pwd
 * @return
 * @throws Exception
 */
public String deleteDeviceType(String query) throws Exception {

    Connection dbConn = null;
    JSONObject obj = new JSONObject();

    try {
        dbConn = DBConnection.createConnection();

        Statement stmt = dbConn.createStatement();
        System.out.println(query);
        stmt.executeUpdate(query);

        obj.put("tag", "delete");
        obj.put("msg", "done");
        obj.put("status", true);

    } catch (SQLException sqle) {
        throw sqle;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return obj.toJSONString();
}