Example usage for java.sql PreparedStatement execute

List of usage examples for java.sql PreparedStatement execute

Introduction

In this page you can find the example usage for java.sql PreparedStatement execute.

Prototype

boolean execute() throws SQLException;

Source Link

Document

Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

Usage

From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java

@Override
public ISQLRowModificationStatus updateQueryValue(ISQLQuery query, ISQLRowResult row, int modifiedColumnIndex,
        Object newValue) throws SQLException {
    final Connection conn = query.getConnection();
    final DatabaseMetaData md = conn.getMetaData();
    // For pending rows, we set the new column value
    if (row.isPending()) {
        row.setValue(modifiedColumnIndex, newValue);
    }//ww  w . j  av a 2s  .co  m
    final ISQLRowModificationStatus status = computeRowModificationStatus(query, row, modifiedColumnIndex);
    // Now processing database update if we can
    if (status.isModifiable()) {
        // Now we can build our query
        String sqlStatement = null;
        final boolean insertNeeded = status.isInsertNeeded();
        if (insertNeeded) {
            sqlStatement = buildInsertStatement(status, md.getIdentifierQuoteString());
        } else {
            sqlStatement = buildUpdateStatement(status, md.getIdentifierQuoteString());
        }
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement(sqlStatement);
            fillPreparedStatement(stmt, !insertNeeded, insertNeeded, row, newValue);
            stmt.execute();
            // Everything was OK, we can unflag any pending row
            if (row.isPending()) {
                row.setPending(false);
            }
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    LOGGER.error("Unable to close SQL update statement: " + e.getMessage(), e);
                }
            }
        }
    }
    return status;
}

From source file:mx.com.pixup.portal.dao.EstadoMunicipioParserDaoJdbc.java

public void parserXML() {

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

        //variables BD
        String sql = "INSERT INTO estado VALUES (?,?)";
        String sqlM = "INSERT INTO municipio VALUES (?,?,?)";
        PreparedStatement preparedStatement;
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        //se obtiene elemento raiz
        Element estado = this.xmlDocumento.getRootElement();
        //elementos 2do nivel
        Element nombre = estado.getChild("nombre");
        Element municipios = estado.getChild("municipios");
        Attribute id = estado.getAttribute("id");
        //construye parametros de la query
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, id.getIntValue());
        preparedStatement.setString(2, nombre.getText());
        preparedStatement.execute();

        List<Element> listaMunicipios = municipios.getChildren("municipio");
        Iterator<Element> i = listaMunicipios.iterator();

        while (i.hasNext()) {
            Element municipio = i.next();
            //Elementos de tercer nivel
            Attribute idMunicipio = municipio.getAttribute("id");
            String nombreMunicipio = municipio.getText();
            //construye parametros de la query
            preparedStatement = connection.prepareStatement(sqlM);
            preparedStatement.setInt(1, idMunicipio.getIntValue());
            preparedStatement.setString(2, nombreMunicipio);
            preparedStatement.setInt(3, id.getIntValue());

            preparedStatement.execute();
        }

        connection.commit();
    } catch (Exception e) {
        //*** se quit el return porque el mtodo es void
        System.out.println(e.getMessage());
    }

}

From source file:com.l2jfree.gameserver.model.clan.L2ClanMember.java

/**
 * Update the characters table of the database with power grade.<BR><BR>
 *//*from   w  ww .  j  av a2 s  .  com*/
public void updatePledgeRank() {
    Connection con = null;

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con
                .prepareStatement("UPDATE characters SET pledge_rank=? WHERE charId=?");
        statement.setLong(1, _pledgeRank);
        statement.setInt(2, getObjectId());
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("could not set char pledge_rank:", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

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

public void testUUID() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("create table test_uuid(id uuid primary key)");
    UUID uuid = new UUID(-2, -1);
    PreparedStatement prep = conn.prepareStatement("insert into test_uuid values(?)");
    prep.setObject(1, uuid);//  ww  w  .j av a2s. c om
    prep.execute();
    ResultSet rs = stat.executeQuery("select * from test_uuid");
    rs.next();
    assertEquals("ffffffff-ffff-fffe-ffff-ffffffffffff", rs.getString(1));
    Object o = rs.getObject(1);
    assertEquals("java.util.UUID", o.getClass().getName());
    stat.execute("drop table test_uuid");
}

From source file:edu.ku.brc.specify.conversion.IdTableMapper.java

/**
 * Copies Mapping table to a destination mapping table.
 * @param dest the insert into table./*  ww  w .j  a v  a 2  s  .  c o  m*/
 */
public void copy(final IdTableMapper dest) {
    PreparedStatement pStmt = null;
    Statement stmt = null;
    try {
        pStmt = oldConn.prepareStatement(String.format("INSERT INTO %s SET OldID=?, NewID=?", dest.getName()));
        stmt = oldConn.createStatement();

        ResultSet rs = stmt.executeQuery("SELECT OldID, NewID FROM " + getName());
        while (rs.next()) {
            pStmt.setInt(1, rs.getInt(1));
            pStmt.setInt(2, rs.getInt(2));
            pStmt.execute();
        }
        rs.close();

    } catch (SQLException ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (pStmt != null)
                pStmt.close();
            if (stmt != null)
                stmt.close();
        } catch (SQLException ex) {
        }
    }
}

From source file:com.talkdesk.geo.GeoCodeRepositoryBuilder.java

/**
 * Populate country data for the table ISO and lang / lat mapping
 *
 * @throws GeoResolverException//from   w  w  w  .  ja va 2 s  . c  o m
 */
public void populateCountryData() throws GeoResolverException {
    try {
        if (connection == null)
            connection = connectToDatabase();

        if (!new File(countryDataLocation).exists()) {
            log.error("No Data file found for countryData. please add to data/country.csv ");
            return;
        }

        Path file = FileSystems.getDefault().getPath(countryDataLocation);
        Charset charset = Charset.forName("UTF-8");
        BufferedReader inputStream = Files.newBufferedReader(file, charset);
        String buffer;
        PreparedStatement preparedStatement;
        preparedStatement = connection.prepareStatement(
                "INSERT INTO countrycodes (COUNTRY_CODE , LATITUDE, LONGITUDE, NAME)" + " VALUES (?,?,?,?)");
        while ((buffer = inputStream.readLine()) != null) {
            String[] values = buffer.split(",");

            preparedStatement.setString(1, values[0].trim());
            preparedStatement.setFloat(2, Float.parseFloat(values[1].trim()));
            preparedStatement.setFloat(3, Float.parseFloat(values[2].trim()));
            preparedStatement.setString(4, values[3].trim());

            preparedStatement.execute();

        }
    } catch (SQLException e) {
        throw new GeoResolverException("Error while executing SQL query", e);
    } catch (IOException e) {
        throw new GeoResolverException("Error while accessing input file", e);
    }

    log.info("Finished populating Database for country data.");
    //should close all the connections for memory leaks.
}

From source file:com.hss.assignment4.RegisterFrame.java

private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed
    if (PassText.getPassword().equals(PassText2.getPassword())) {
        Connection connect = null;
        ResultSet rs = null;/*from   w w  w . j a va2 s. c o m*/
        PreparedStatement pst = null;
        String sql = "INSERT Into login (UserName, Password) VALUES (?, ?) ON DUPLICATE KEY UPDATE UserName = VALUES(UserName)";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/chatuser&pass?zeroDateTimeBehavior=convertToNull", "root",
                    "Insane!touhou999");
            pst = connect.prepareStatement(sql);
            pst.setString(1, UserText.getText());
            pst.setString(2, hashing(PassText.getText()));
            pst.execute();
            connect.close();
        } catch (SQLException e) {
            Logger.getLogger(RegisterFrame.class.getName()).log(Level.SEVERE, null, e);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(RegisterFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(RegisterFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        setVisible(false);
    } else {
        JOptionPane.showMessageDialog(null, "Password Not Matched");
    }
}

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

public void testSetObject() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("CREATE TABLE TEST(C CHAR(1))");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?)");
    prep.setObject(1, 'x');
    prep.execute();
    stat.execute("DROP TABLE TEST");
    stat.execute("CREATE TABLE TEST(ID INT, DATA BINARY, JAVA OTHER)");
    prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?)");
    prep.setInt(1, 1);/*from   w w  w. jav  a  2  s.  c  om*/
    prep.setObject(2, 11);
    prep.setObject(3, null);
    prep.execute();
    prep.setInt(1, 2);
    prep.setObject(2, 101, Types.OTHER);
    prep.setObject(3, 103, Types.OTHER);
    prep.execute();
    PreparedStatement p2 = conn.prepareStatement("SELECT * FROM TEST ORDER BY ID");
    ResultSet rs = p2.executeQuery();
    rs.next();
    Object o = rs.getObject(2);
    assertTrue(o instanceof byte[]);
    assertTrue(rs.getObject(3) == null);
    rs.next();
    o = rs.getObject(2);
    assertTrue(o instanceof byte[]);
    o = rs.getObject(3);
    assertTrue(o instanceof Integer);
    assertEquals(103, ((Integer) o).intValue());
    assertFalse(rs.next());
    stat.execute("DROP TABLE TEST");
}

From source file:com.geodetix.geo.dao.PostGisGeometryDAOImpl.java

/**
 * PostGIS implementation of the /* ww  w . j a v a 2 s  . c o  m*/
 * {@link com.geodetix.geo.interfaces.GeometryLocalHome#dropDbTable()}
 * method removing the table related to the EJBs.
 */
public void dropDbTable() {

    PreparedStatement pstm = null;
    Connection con = null;

    try {

        con = this.dataSource.getConnection();

        System.out.println("Dropping Bean Table... ");

        pstm = con.prepareStatement(PostGisGeometryDAO.DROP_TABLE_STATEMENT);
        pstm.execute();

        System.out.println("...done!");

    } catch (SQLException e) {

        throw new EJBException(e);

    } finally {

        try {
            if (pstm != null) {
                pstm.close();
            }
        } catch (Exception e) {
        }

        try {
            if (con != null) {
                con.close();
            }

        } catch (Exception e) {
        }
    }
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

/**
 * Delete an entry./*from ww w  . java2s  .c  om*/
 * 
 * @param connection
 *        The connection
 * @param key
 *        The key
 * @throws SQLException
 */
private void delete(Connection connection, String key) throws SQLException {
    Lock lock = lockSource.getWriteLock(key);
    lock.lock();
    try {
        String sql = "DELETE FROM " + cacheTableName + " WHERE key=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        try {
            statement.setString(1, key);
            if (!statement.execute()) {
                if (logger.isLoggable(Level.FINE) && statement.getUpdateCount() > 0)
                    logger.fine("Deleted: " + key);
            }
        } finally {
            statement.close();
        }
    } finally {
        lock.unlock();
        lockSource.discard(key);
    }
}