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.googlecode.fascinator.portal.services.impl.DatabaseServicesImpl.java

/**
 * Top level wrapper to execute simple non-returning SQL, such as create or
 * update statements./*w w  w.  j a v  a2  s  .  com*/
 * 
 * @param db The database connection to use.
 * @param index The index to file this statement under for caching.
 * @param sql The sql string to execute.
 * @param fields The data to bind against placeholders. NULL is valid.
 * @throws Exception if there is an error.
 */
@Override
public void execute(String db, String index, String sql, List<Object> fields) throws Exception {
    // Sanity checks
    if (db == null) {
        throw new Exception("Database cannot be NULL!");
    }
    if (sql == null) {
        throw new Exception("SQL statement cannot be NULL!");
    }

    // Establish a database connection
    Connection database = checkConnection(db);
    if (database == null) {
        throw new Exception("Database '" + db + "' does not exist!");
    }

    // Build our query
    PreparedStatement statement = prepare(database, index, sql);
    if (fields != null) {
        for (int i = 1; i <= fields.size(); i++) {
            bindParam(statement, i, fields.get(i - 1));
        }
    }

    // Done
    statement.execute();
}

From source file:com.akman.excel.view.frmExportExcel.java

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    Connection conn = Javaconnect.ConnecrDb();
    PreparedStatement pst = null;
    ResultSet rs = null;//from w  w w  .  ja v a2  s.  co  m
    try {
        //            String sql = "INSERT INTO ExcelData (Image) VALUES (?)";
        String sql = "Update ExcelData SET Image = ? ";
        pst = conn.prepareStatement(sql);

        pst.setBytes(1, person_image);

        pst.execute();

        System.out.println(person_image);

        JOptionPane.showMessageDialog(null, "Update Image");

        getImage();

    } catch (SQLException ex) {
        Logger.getLogger(frmSelectImage.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pst);
        DbUtils.closeQuietly(conn);
    }
}

From source file:lineage2.gameserver.tables.ClanTable.java

/**
 * Method stopClanWar.// w  w  w . java  2 s.c  o m
 * @param clan1 Clan
 * @param clan2 Clan
 */
public void stopClanWar(Clan clan1, Clan clan2) {
    clan1.deleteEnemyClan(clan2);
    clan2.deleteAttackerClan(clan1);
    clan1.broadcastClanStatus(false, false, true);
    clan2.broadcastClanStatus(false, false, true);
    Connection con = null;
    PreparedStatement statement = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? AND clan2=?");
        statement.setInt(1, clan1.getClanId());
        statement.setInt(2, clan2.getClanId());
        statement.execute();
    } catch (Exception e) {
        _log.warn("could not delete war data:" + e);
    } finally {
        DbUtils.closeQuietly(con, statement);
    }
    clan1.broadcastToOnlineMembers(new SystemMessage(SystemMessage.THE_WAR_AGAINST_S1_CLAN_HAS_BEEN_STOPPED)
            .addString(clan2.getName()));
    clan2.broadcastToOnlineMembers(
            new SystemMessage(SystemMessage.S1_CLAN_HAS_STOPPED_THE_WAR).addString(clan1.getName()));
}

From source file:com.wso2telco.dep.operatorservice.dao.BlackListWhiteListDAO.java

public void removeWhitelistNumber(String userMSISDN) throws Exception {

    StringBuilder sql = new StringBuilder();
    sql.append("DELETE FROM ");
    sql.append(OparatorTable.SUBSCRIPTION_WHITELIST.getTObject());
    sql.append(" WHERE `MSISDN`=?;");

    Connection conn = null;/*from www.j a  va 2s  .c  o  m*/
    PreparedStatement ps = null;

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        ps = conn.prepareStatement(sql.toString());
        ps.setString(1, userMSISDN);
        ps.execute();
    } catch (Exception e) {
        throw e;
    } finally {
        DbUtils.closeAllConnections(ps, conn, null);
    }
}

From source file:lineage2.gameserver.tables.ClanTable.java

/**
 * Method startClanWar./*from   w  w w .j  av a2s  .c om*/
 * @param clan1 Clan
 * @param clan2 Clan
 */
public void startClanWar(Clan clan1, Clan clan2) {
    clan1.setEnemyClan(clan2);
    clan2.setAttackerClan(clan1);
    clan1.broadcastClanStatus(false, false, true);
    clan2.broadcastClanStatus(false, false, true);
    Connection con = null;
    PreparedStatement statement = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement("REPLACE INTO clan_wars (clan1, clan2) VALUES(?,?)");
        statement.setInt(1, clan1.getClanId());
        statement.setInt(2, clan2.getClanId());
        statement.execute();
    } catch (Exception e) {
        _log.warn("could not store clan war data:" + e);
    } finally {
        DbUtils.closeQuietly(con, statement);
    }
    clan1.broadcastToOnlineMembers(new SystemMessage(
            SystemMessage.CLAN_WAR_HAS_BEEN_DECLARED_AGAINST_S1_CLAN_IF_YOU_ARE_KILLED_DURING_THE_CLAN_WAR_BY_MEMBERS_OF_THE_OPPOSING_CLAN_THE_EXPERIENCE_PENALTY_WILL_BE_REDUCED_TO_1_4_OF_NORMAL)
                    .addString(clan2.getName()));
    clan2.broadcastToOnlineMembers(
            new SystemMessage(SystemMessage.S1_CLAN_HAS_DECLARED_CLAN_WAR).addString(clan1.getName()));
}

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

public void parserXML() {

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

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

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

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

}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * With this method the devices can subscribe. Names as ID have to be
 * defined. The devices of the first component are saved in the table
 * "InputDevices". The devices of the second component are saved in the
 * table "OutputDevices"./*w  w  w  .  j a va 2  s .  c o  m*/
 * 
 * @param component
 *            1 or 2
 * @param classes
 *            name of the class the device belong to
 * @param name
 *            name to be chosen
 */
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@Path("/anmelden/{component}/{classes}/{name}")
public static synchronized String subscribe(@PathParam("component") int component,
        @PathParam("classes") String classes, @PathParam("name") String name) {
    String ok = "ok";
    createDBConnection();
    name.replaceAll("\"", "\\\"");
    try {
        if (component == 1) {
            PreparedStatement st = conn.prepareStatement("select class from \"Classes\" where class=?");
            st.setString(1, classes);
            ResultSet result = st.executeQuery();
            if (result.next()) {
                Statement statement = conn.createStatement();
                statement.execute("insert into \"" + classes + "\"(nameinput) values ('" + name + "');");
                st = conn.prepareStatement("insert into \"InputDevices\"(class,name) values (?,?);");
                st.setString(1, classes);
                st.setString(2, name);
                st.execute();

            } else {
                ok = "class not found";
            }

        }

        if (component == 2) {
            PreparedStatement st = conn.prepareStatement("select class from \"Classes\"where class=?");
            st.setString(1, classes);
            ResultSet result = st.executeQuery();
            if (result.next()) {
                deviceActive.put(classes + "," + name, true);
                createDBConnection();
                st = conn.prepareStatement(
                        "insert into \"OutputDevices\"(class,topic,enabled) values (?,?,'t');");
                st.setString(1, classes);
                st.setString(2, name);
                st.execute();

            } else {
                ok = "class not found";
            }
        }

    } catch (SQLException e) {

        String message = e.getMessage();
        if (!message.contains("doppelter Schlsselwert")) {
            logger.error("SQL Exception", e);
        }

    }
    closeDBConnection();
    return ok;
}

From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java

public void insert(WellKnownAttribute wko) throws SQLException {
    PreparedStatement s = connection.prepareStatement(String.format(
            "INSERT into %s (id, name, description, updated_by, value_type) VALUES (?, ?, ?, ?, ?)",
            wko.tableName()));//from   w  w  w .j a  v  a  2s. co m
    try {
        s.setString(1, wko.id());
        s.setString(2, wko.wkoName());
        s.setString(3, wko.description());
        s.setString(4, WellKnownAgency.CORE.id());
        s.setInt(5, wko.valueType().ordinal());
        s.execute();
    } catch (SQLException e) {
        throw new SQLException(String.format("Unable to insert %s", wko), e);
    }
}

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

/**
 * PostGIS implementation of the /*from w  ww  . ja  v a  2s  . c  o  m*/
 * {@link com.geodetix.geo.interfaces.GeometryLocalHome#makeDbTable(java.lang.String, int, int)}
 * method creating an OpenGIS compliant table in the PostGIS database.
 * The table will contain the geometry EJBs.
 *
 * @param gemetryType the string that rapresent a valid PostGIS 
 * geometry type (i.e.: POINT, LINESTRING, POLYGON etc.).
 * @param srid the SRID of the geometry.
 * @param geometryDimension the dimension of the geometry.
 */
public void makeDbTable(String gemetryType, int srid, int geometryDimension) {

    PreparedStatement pstm = null;
    Connection con = null;

    try {

        con = this.dataSource.getConnection();

        System.out.println("Creating OpenGIS Bean table...");

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

        pstm = con.prepareStatement(PostGisGeometryDAO.ADD_OPEN_GIS_GEOMETRY_COLUMN_STATEMENT);
        pstm.setInt(1, srid);
        pstm.setString(2, gemetryType);
        pstm.setInt(3, geometryDimension);

        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.chiralbehaviors.CoRE.kernel.Bootstrap.java

public void insertNetwork(WellKnownObject wko) throws SQLException {
    String tableName = wko.tableName() + "_network";
    PreparedStatement s = connection.prepareStatement(String.format(
            "INSERT into %s (id, parent, relationship, child, updated_by) VALUES (?, ?, ?, ?, ?)", tableName));
    try {// w  w  w.  ja  v a2s  . c om
        s.setString(1, UuidGenerator.toBase64(new UUID(0, 0)));
        s.setString(2, wko.id());
        s.setString(3, WellKnownRelationship.RELATIONSHIP.id());
        s.setString(4, wko.id());
        s.setString(5, WellKnownAgency.CORE.id());
        s.execute();
    } catch (SQLException e) {
        throw new SQLException(String.format("Unable to insert root %s", tableName), e);
    }
}