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:dsd.dao.DAOProvider.java

/**
 * calls the correct method for setting the command parameter depending on
 * parameter type//w  ww.j a  v a 2s .  c o m
 * 
 * @param command
 * @param object
 * @param parameterIndex
 * @throws SQLException
 */
private static void SetParameter(PreparedStatement command, Object object, int parameterIndex)
        throws SQLException {
    if (object instanceof Timestamp) {
        command.setTimestamp(parameterIndex, (Timestamp) object);
    } else if (object instanceof String) {
        command.setString(parameterIndex, (String) object);
    } else if (object instanceof Long) {
        command.setLong(parameterIndex, (Long) object);
    } else if (object instanceof Integer) {
        command.setInt(parameterIndex, (Integer) object);
    } else if (object instanceof Boolean) {
        command.setBoolean(parameterIndex, (Boolean) object);
    } else if (object instanceof Float) {
        command.setFloat(parameterIndex, (Float) object);
    } else {
        throw new IllegalArgumentException(
                "type needs to be inserted in Set parameter method of DAOProvider class");
    }

}

From source file:module.entities.NameFinder.DB.java

public static void InsertNewLemma2DB(String lemma, String category) throws SQLException {
    String selectSQL = "SELECT * FROM  WHERE  = ? ";
    PreparedStatement preparedStatement = connection.prepareStatement(selectSQL);
    preparedStatement.setString(1, lemma);
    preparedStatement.setString(2, category);
    ResultSet rs = preparedStatement.executeQuery();
    String insertSQL = "INSERT INTO  " + "(lemma_text,lemma_category) VALUES" + "(?,?)";
    PreparedStatement prepStatement = connection.prepareStatement(insertSQL);
    int id = -1;/*  ww w . j av  a2s . c  o  m*/
    if (rs.next()) {
        id = rs.getInt(1);
    } else {
        prepStatement.setString(1, lemma);
        prepStatement.setString(2, category);
        prepStatement.addBatch();
    }
    prepStatement.executeBatch();
    prepStatement.close();
}

From source file:com.keybox.manage.db.UserDB.java

/**
 * checks to see if username is unique while ignoring current user
 *
 * @param userId user id/*from   w w  w . ja  v  a 2 s. c  o m*/
 * @param username username
 * @return true false indicator
 */
public static boolean isUnique(Long userId, String username) {

    boolean isUnique = true;
    if (userId == null) {
        userId = -99L;
    }

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement(
                "select * from users where enabled=true and lower(username) like lower(?) and id != ?");
        stmt.setString(1, username);
        stmt.setLong(2, userId);
        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            isUnique = false;
        }
        DBUtils.closeRs(rs);
        DBUtils.closeStmt(stmt);
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }
    DBUtils.closeConn(con);

    return isUnique;

}

From source file:com.tethrnet.manage.db.AuthDB.java

/**
 * auth user and return auth token if valid auth
 *
 * @param auth username and password object
 * @return auth token if success//w w w . j a v a2 s  .c  o m
 */
public static String login(Auth auth) {
    String authToken = null;
    //admin just for locally
    if (!auth.getUsername().equals("admin")) {
        //check ldap first
        authToken = ExternalAuthUtil.login(auth);
    }

    if (StringUtils.isEmpty(authToken)) {

        Connection con = null;

        try {
            con = DBUtils.getConn();

            //get salt for user
            String salt = getSaltByUsername(con, auth.getUsername());
            //login
            PreparedStatement stmt = con
                    .prepareStatement("select * from users where enabled=true and username=? and password=?");
            stmt.setString(1, auth.getUsername());
            stmt.setString(2, EncryptionUtil.hash(auth.getPassword() + salt));
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {

                auth.setId(rs.getLong("id"));
                authToken = UUID.randomUUID().toString();
                auth.setAuthToken(authToken);
                auth.setAuthType(Auth.AUTH_BASIC);
                updateLogin(con, auth);

            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

        } catch (Exception e) {
            log.error(e.toString(), e);
        }

        DBUtils.closeConn(con);
    }

    return authToken;

}

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

public static void getSupplierOfCoffee(String coffeeName, String[] supplierName) throws SQLException {
    Connection con = DriverManager.getConnection("jdbc:default:connection");
    PreparedStatement pstmt = null;
    ResultSet rs = null;//  w  w  w. j  ava2  s  . c o  m

    String query = "select SUPPLIERS.SUP_NAME " + "from SUPPLIERS, COFFEES "
            + "where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "and ? = COFFEES.COF_NAME";

    pstmt = con.prepareStatement(query);
    pstmt.setString(1, coffeeName);
    rs = pstmt.executeQuery();

    if (rs.next()) {
        supplierName[0] = rs.getString(1);
    } else {
        supplierName[0] = null;
    }
}

From source file:com.keybox.manage.db.UserDB.java

/**
 * updates existing user/*  w  w w . j av  a2  s  .  c o m*/
 * @param user user object
 */
public static void updateUserCredentials(User user) {

    Connection con = null;
    try {
        con = DBUtils.getConn();
        String salt = EncryptionUtil.generateSalt();
        PreparedStatement stmt = con.prepareStatement(
                "update users set first_nm=?, last_nm=?, email=?, username=?, user_type=?, password=?, salt=? where id=?");
        stmt.setString(1, user.getFirstNm());
        stmt.setString(2, user.getLastNm());
        stmt.setString(3, user.getEmail());
        stmt.setString(4, user.getUsername());
        stmt.setString(5, user.getUserType());
        stmt.setString(6, EncryptionUtil.hash(user.getPassword() + salt));
        stmt.setString(7, salt);
        stmt.setLong(8, user.getId());
        stmt.execute();
        DBUtils.closeStmt(stmt);
        if (User.ADMINISTRATOR.equals(user.getUserType())) {
            PublicKeyDB.deleteUnassignedKeysByUser(con, user.getId());
        }

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    DBUtils.closeConn(con);

}

From source file:com.concursive.connect.web.webdav.WebdavManager.java

/**
 * Gets the webdavPassword attribute of the WebdavManager object
 *
 * @param db       Description of the Parameter
 * @param username Description of the Parameter
 * @return The webdavPassword value/*w w  w. ja v  a  2 s  .  c o  m*/
 * @throws SQLException Description of the Exception
 */
public static String getWebdavPassword(Connection db, String username) throws SQLException {
    String password = "";
    PreparedStatement pst = db.prepareStatement(
            "SELECT webdav_password " + "FROM users " + "WHERE username = ? " + "AND enabled = ? ");
    pst.setString(1, username);
    pst.setBoolean(2, true);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        password = rs.getString("webdav_password");
    }
    rs.close();
    pst.close();
    return password;
}

From source file:ca.qc.adinfo.rouge.leaderboard.db.LeaderboardDb.java

public static boolean submitScore(DBManager dbManager, String key, long userId, long score) {

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;/*from www .j a  v a 2  s . c  o  m*/
    String sql = null;

    sql = "INSERT INTO rouge_leaderboard_score (`leaderboard_key`, `user_id`, `score`) "
            + "VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE score = GREATEST(?, score);";

    try {
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);

        stmt.setString(1, key);
        stmt.setLong(2, userId);
        stmt.setLong(3, score);
        stmt.setLong(4, score);

        int ret = stmt.executeUpdate();

        return (ret > 0);

    } catch (SQLException e) {
        log.error(stmt);
        log.error(e);
        return false;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.keybox.manage.db.AuthDB.java

/**
 * checks to see if user is an admin based on auth token
 *
 * @param userId    user id//from www .  j  ava  2  s. c  o m
 * @param authToken auth token string
 * @return user type if authorized, null if not authorized
 */
public static String isAuthorized(Long userId, String authToken) {

    String authorized = null;

    Connection con = null;
    if (authToken != null && !authToken.trim().equals("")) {

        try {
            con = DBUtils.getConn();
            PreparedStatement stmt = con
                    .prepareStatement("select * from users where enabled=true and id=? and auth_token=?");
            stmt.setLong(1, userId);
            stmt.setString(2, authToken);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                authorized = rs.getString("user_type");

            }
            DBUtils.closeRs(rs);

            DBUtils.closeStmt(stmt);

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
    DBUtils.closeConn(con);
    return authorized;

}

From source file:com.wso2telco.dao.TransactionDAO.java

/**
 * Insert transaction log.//from  w  w  w . j  a v a 2 s  . c  o m
 *
 * @param transaction the transaction
 * @param contextId   the context id
 * @param statusCode  the status code
 * @throws Exception the exception
 */
public static void insertTransactionLog(Transaction transaction, String contextId, int statusCode)
        throws Exception {

    Connection conn = null;
    PreparedStatement ps = null;
    try {
        conn = DbUtil.getConnectDBConnection();
        String query = "INSERT INTO mcx_cross_operator_transaction_log (tx_id, tx_status, batch_id, api_id, "
                + "client_id," + " application_state, sub_op_mcc, sub_op_mnc, timestamp_start, timestamp_end, "
                + "exchange_response_code)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        ps = conn.prepareStatement(query);
        ps.setString(1, transaction.getTx_id());
        ps.setString(2, transaction.getTx_status());
        ps.setString(3, contextId);
        ps.setString(4, transaction.getApi().getId());
        ps.setString(5, transaction.getClient_id());
        ps.setString(6, transaction.getApplication_state());
        ps.setString(7, transaction.getSubscriber_operator().getMcc());
        ps.setString(8, transaction.getSubscriber_operator().getMnc());
        ps.setString(9, transaction.getTimestamp().getStart());
        ps.setString(10, transaction.getTimestamp().getEnd());
        ps.setInt(11, statusCode);
        ps.execute();

    } catch (SQLException e) {
        handleException("Error in inserting transaction log record : " + e.getMessage(), e);
    } finally {
        DbUtil.closeAllConnections(ps, conn, null);
    }
}