Example usage for java.sql PreparedStatement setString

List of usage examples for java.sql PreparedStatement setString

Introduction

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

Prototype

void setString(int parameterIndex, String x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java String value.

Usage

From source file:com.taobao.tddl.common.sync.RowBasedReplicationExecutor.java

/**
 * jdbcdelete//from  www.  j  a v a  2s  .c  om
 */
public static void batchDeleteSyncLog(Collection<RowBasedReplicationContext> contexts) {
    long timeused, time0 = System.currentTimeMillis();
    String sqlpattern = "delete from sync_log_{0} where id = ?";

    /**
     * RowBasedReplicationContextupdateSql
     */
    Map<JdbcTemplate, Map<String/*logSQL*/, List<RowBasedReplicationContext>>> sortedContexts = buildSortedContexts(
            contexts, sqlpattern.toString());

    for (Map.Entry<JdbcTemplate, Map<String, List<RowBasedReplicationContext>>> e0 : sortedContexts
            .entrySet()) {
        JdbcTemplate jt = e0.getKey();
        for (Map.Entry<String, List<RowBasedReplicationContext>> e : e0.getValue().entrySet()) {
            final List<RowBasedReplicationContext> endContexts = e.getValue();
            BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() {
                public int getBatchSize() {
                    return endContexts.size();
                }

                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    RowBasedReplicationContext context = endContexts.get(i);
                    ps.setString(1, context.getSyncLogId());
                }
            };
            jt.batchUpdate(e.getKey(), setter);
            if (log.isDebugEnabled()) {
                log.debug("[batchDeleteSyncLog], sql = [" + e.getKey() + "], batch size=" + endContexts.size());
            }
        }
    }
    timeused = System.currentTimeMillis() - time0;
    log.warn(contexts.size() + " replication logs deleted, time used:" + timeused);
    Monitor.add(Monitor.KEY1, Monitor.KEY2_SYNC, Monitor.KEY3_BatchDeleteSyncLog, contexts.size(), timeused);
}

From source file:com.splicemachine.derby.utils.SpliceAdmin.java

/**
 * Be Careful when using this, as it will return conglomerate ids for all the indices of a table
 * as well as the table itself. While the first conglomerate SHOULD be the main table, there
 * really isn't a guarantee, and it shouldn't be relied upon for correctness in all cases.
 *//*from w  w  w  . j  a va  2s.  c om*/
public static long[] getConglomNumbers(Connection conn, String schemaName, String tableName)
        throws SQLException {
    List<Long> conglomIDs = new ArrayList<>();
    if (schemaName == null)
        // default schema
        schemaName = SQLConfiguration.SPLICE_USER;

    String query;
    boolean isTableNameEmpty;

    if (tableName == null) {
        query = getSqlConglomsInSchema();
        isTableNameEmpty = true;
    } else {
        query = getSqlConglomsInTable();
        isTableNameEmpty = false;
    }

    ResultSet rs = null;
    PreparedStatement s = null;
    try {
        s = conn.prepareStatement(query);
        s.setString(1, schemaName.toUpperCase());
        if (!isTableNameEmpty) {
            s.setString(2, tableName.toUpperCase());
        }
        rs = s.executeQuery();
        while (rs.next()) {
            conglomIDs.add(rs.getLong(1));
        }

        if (conglomIDs.isEmpty()) {
            if (isTableNameEmpty) {
                throw PublicAPI
                        .wrapStandardException(ErrorState.LANG_SCHEMA_DOES_NOT_EXIST.newException(schemaName));
            }
            throw PublicAPI.wrapStandardException(ErrorState.LANG_TABLE_NOT_FOUND.newException(tableName));
        }
    } finally {
        if (rs != null)
            rs.close();
        if (s != null)
            s.close();
    }
    if (conglomIDs.isEmpty()) {
        return new long[0];
    }
    long[] congloms = new long[conglomIDs.size()];
    for (int i = 0; i < conglomIDs.size(); i++) {
        congloms[i] = conglomIDs.get(i);
    }
    /*
     * An index conglomerate id can be returned by the query before the main table one is,
    * but it should ALWAYS have a higher conglomerate id, so if we sort the congloms,
    * we should return the main table before any of its indices.
    */
    Arrays.sort(congloms);
    return congloms;
}

From source file:com.stratelia.webactiv.util.DBUtil.java

protected static int getMaxId(Connection privateConnection, String tableName, String idName)
        throws SQLException {
    // tentative d'update
    SilverTrace.debug("util", "DBUtil.getNextId", "dBName = " + tableName);
    try {/*from w ww .  ja  va2  s  . c om*/
        int max = updateMaxFromTable(privateConnection, tableName);
        privateConnection.commit();
        return max;
    } catch (Exception e) {
        // l'update n'a rien fait, il faut recuperer une valeur par defaut.
        // on recupere le max (depuis la table existante du composant)
        SilverTrace.debug("util", "DBUtil.getNextId",
                "impossible d'updater, if faut recuperer la valeur initiale", e);
    }
    int max = getMaxFromTable(privateConnection, tableName, idName);
    PreparedStatement createStmt = null;
    try {
        // on enregistre le max
        String createStatement = "INSERT INTO UniqueId (maxId, tableName) VALUES (?, ?)";
        createStmt = privateConnection.prepareStatement(createStatement);
        createStmt.setInt(1, max);
        createStmt.setString(2, tableName.toLowerCase());
        createStmt.executeUpdate();
        privateConnection.commit();
        return max;
    } catch (Exception e) {
        // impossible de creer, on est en concurence, on reessaye l'update.
        SilverTrace.debug("util", "DBUtil.getNextId", "impossible de creer, if faut reessayer l'update", e);
        rollback(privateConnection);
    } finally {
        close(createStmt);
    }
    max = updateMaxFromTable(privateConnection, tableName);
    privateConnection.commit();
    return max;
}

From source file:net.sf.l2j.gameserver.model.entity.L2JOneoRusEvents.DM.java

public static void saveData() {
    java.sql.Connection con = null;
    try {/*from  w  ww  . j  av  a2 s  .  c om*/
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement;
        statement = con.prepareStatement("Delete from dm");
        statement.execute();
        statement.close();
        statement = con.prepareStatement(
                "INSERT INTO dm (eventName, eventDesc, joiningLocation, minlvl, maxlvl, npcId, npcX, npcY, npcZ, rewardId, rewardAmount, color, playerX, playerY, playerZ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        statement.setString(1, _eventName);
        statement.setString(2, _eventDesc);
        statement.setString(3, _joiningLocationName);
        statement.setInt(4, _minlvl);
        statement.setInt(5, _maxlvl);
        statement.setInt(6, _npcId);
        statement.setInt(7, _npcX);
        statement.setInt(8, _npcY);
        statement.setInt(9, _npcZ);
        statement.setInt(10, _rewardId);
        statement.setInt(11, _rewardAmount);
        statement.setInt(12, _playerColors);
        statement.setInt(13, _playerX);
        statement.setInt(14, _playerY);
        statement.setInt(15, _playerZ);
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.error("Exception: DM.saveData(): " + e.getMessage());
    } finally {
        try {
            con.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

/**
 * Recupera la fecha de pago o cobro de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura//w w  w . j  a va 2s  . c om
 */
public static Date[] getFechaFacturaMigrated(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    Date[] result = new Date[0];

    try {
        log.info("RECOVERING FECHAS " + billType + " MIGRADAS");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS vacio.

        String sql = "SELECT bp.expirationDate FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ? order by bp.expirationDate";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);

        rs = pstmt.executeQuery();

        rs.last();
        result = new Date[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDate(1);
            log.info("\t" + result[counter]);
            counter++;
        }

    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }

    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/*from w ww.  j ava2s  . c  om*/
 */
public static double[] getImporteFacturaMigrated(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double[] result = new double[0];

    try {
        log.info("RECOVERING IMPORTE FACTURAS " + billType + " MIGRADAS");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); // NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS vacio         

        String sql = "SELECT bp.amount FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ? order by amount";

        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);
        rs = pstmt.executeQuery();

        rs.last();
        result = new double[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDouble(1);
            log.info("\t" + result[counter]);
            counter++;
        }

    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }

    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java

/**
 * Update user details in Back Channeling Scenario : update oauth code
 *
 * @param code          Auth code//w  ww  .  j a v  a  2 s  .  co m
 * @param correlationId unique ID of the request
 */
public static void updateCodeInBackChannel(String correlationId, String code)
        throws ConfigurationException, CommonAuthenticatorException {

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    String updateUserDetailsQuery = null;

    updateUserDetailsQuery = "update backchannel_request_details set auth_code=? where correlation_id=?";

    try {
        connection = getConnectDBConnection();

        if (log.isDebugEnabled()) {
            log.debug("Executing the query " + updateUserDetailsQuery);
        }

        preparedStatement = connection.prepareStatement(updateUserDetailsQuery);
        preparedStatement.setString(1, code);
        preparedStatement.setString(2, correlationId);
        preparedStatement.executeUpdate();

    } catch (SQLException e) {
        handleException("Error occurred while updating user details for : " + correlationId + "in "
                + "BackChannel Scenario.", e);
    } catch (NamingException e) {
        throw new ConfigurationException("DataSource could not be found in mobile-connect.xml");
    } finally {
        closeAllConnections(preparedStatement, connection);
    }
}

From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java

/**
 * Update user details in Back Channeling Scenario : update Session ID
 *
 * @param sessionId     ID of the session
 * @param correlationId unique ID of the user
 *//*from www .  j ava2 s . c o m*/
public static void updateSessionIdInBackChannel(String correlationId, String sessionId)
        throws ConfigurationException, CommonAuthenticatorException {

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    String updateUserDetailsQuery = null;

    updateUserDetailsQuery = "update backchannel_request_details set session_id=? where correlation_id=?;";

    try {
        connection = getConnectDBConnection();

        if (log.isDebugEnabled()) {
            log.debug("Executing the query " + updateUserDetailsQuery);
        }

        preparedStatement = connection.prepareStatement(updateUserDetailsQuery);
        preparedStatement.setString(1, sessionId);
        preparedStatement.setString(2, correlationId);
        preparedStatement.executeUpdate();

    } catch (SQLException e) {
        handleException("Error occurred while updating user details for : " + correlationId + "in "
                + "BackChannel Scenario.", e);
    } catch (NamingException e) {
        throw new ConfigurationException("DataSource could not be found in mobile-connect.xml");
    } finally {
        closeAllConnections(preparedStatement, connection);
    }
}

From source file:com.stratelia.webactiv.util.DBUtil.java

/**
 * Centralization in order to sets the parameters on a prepare statement.
 * @param preparedStatement//from w ww.ja va2s . co m
 * @param parameters
 * @throws SQLException
 */
public static <O> void setParameters(PreparedStatement preparedStatement, Collection<O> parameters)
        throws SQLException {
    int paramIndex = 1;
    for (Object parameter : parameters) {
        if (parameter == null) {
            preparedStatement.setObject(paramIndex, null);
        } else if (parameter instanceof String) {
            preparedStatement.setString(paramIndex, (String) parameter);
        } else if (parameter instanceof Enum) {
            preparedStatement.setString(paramIndex, ((Enum) parameter).name());
        } else if (parameter instanceof Integer) {
            preparedStatement.setInt(paramIndex, (Integer) parameter);
        } else if (parameter instanceof Long) {
            preparedStatement.setLong(paramIndex, (Long) parameter);
        } else if (parameter instanceof Timestamp) {
            preparedStatement.setTimestamp(paramIndex, (Timestamp) parameter);
        } else if (parameter instanceof Date) {
            preparedStatement.setDate(paramIndex, new java.sql.Date(((Date) parameter).getTime()));
        } else if (parameter instanceof UserDetail) {
            preparedStatement.setString(paramIndex, ((UserDetail) parameter).getId());
        } else {
            throw new IllegalArgumentException("SQL parameter type not handled: " + parameter.getClass());
        }
        paramIndex++;
    }
}

From source file:com.wso2telco.gsma.authenticators.DBUtils.java

public static void insertHashKeyContextIdentifierMapping(String hashKey, String contextIdentifier)
        throws AuthenticatorException {
    String sql = "insert into sms_hashkey_contextid_mapping(hashkey, contextid) values  (?,?);";

    if (log.isDebugEnabled()) {
        log.debug("Executing the query " + sql + " for hash key " + hashKey + " and context identifier "
                + contextIdentifier);//from   w w  w .  j  a v  a2  s.c  o  m
    }

    Connection connection = null;
    PreparedStatement ps = null;
    try {
        connection = getConnectDBConnection();
        ps = connection.prepareStatement(sql.toString());
        ps.setString(1, hashKey);
        ps.setString(2, contextIdentifier);
        ps.executeUpdate();
    } catch (SQLException e) {
        handleException(e.getMessage(), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
}