Example usage for java.sql Connection prepareStatement

List of usage examples for java.sql Connection prepareStatement

Introduction

In this page you can find the example usage for java.sql Connection prepareStatement.

Prototype

PreparedStatement prepareStatement(String sql) throws SQLException;

Source Link

Document

Creates a PreparedStatement object for sending parameterized SQL statements to the database.

Usage

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

/**
 * inserts new profile//w  w w.j a  v  a 2 s  .  c o m
 *
 * @param profile profile object
 */
public static void insertProfile(Profile profile) {

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement("insert into profiles (nm, desc) values (?,?)");
        stmt.setString(1, profile.getNm());
        stmt.setString(2, profile.getDesc());
        stmt.execute();
        DBUtils.closeStmt(stmt);

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

From source file:Main.java

public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters)
        throws SQLException {
    List<Map<String, Object>> results = null;
    PreparedStatement ps = null;/*  w  w w .j  a va  2s.  co  m*/
    ResultSet rs = null;
    try {
        ps = connection.prepareStatement(sql);

        int i = 0;
        for (Object parameter : parameters) {
            ps.setObject(++i, parameter);
        }
        rs = ps.executeQuery();
        results = map(rs);
    } finally {
        close(rs);
        close(ps);
    }
    return results;
}

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

/**
 * updates profile//from w w w.  jav a  2s. c o m
 *
 * @param profile profile object
 */
public static void updateProfile(Profile profile) {

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement("update profiles set nm=?, desc=? where id=?");
        stmt.setString(1, profile.getNm());
        stmt.setString(2, profile.getDesc());
        stmt.setLong(3, profile.getId());
        stmt.execute();
        DBUtils.closeStmt(stmt);

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

From source file:com.silverpeas.notation.model.RatingDAO.java

public static long moveRatings(Connection con, ContributionRatingPK pk, final String componentInstanceId)
        throws SQLException {
    PreparedStatement prepStmt = con.prepareStatement(QUERY_MOVE_RATINGS);
    try {/*from w w  w.ja v a  2  s  . c  o m*/
        prepStmt.setString(1, componentInstanceId);
        prepStmt.setString(2, pk.getInstanceId());
        prepStmt.setString(3, pk.getContributionId());
        prepStmt.setString(4, pk.getContributionType());
        return prepStmt.executeUpdate();
    } finally {
        DBUtil.close(prepStmt);
    }
}

From source file:fll.JudgeInformation.java

/**
 * Get all judges stored for this tournament.
 * /*from  w w  w  .j  a v a  2  s  .c  om*/
 * @param connection the database
 * @param tournament tournament ID
 * @return the judges
 * @throws SQLException
 */
public static Collection<JudgeInformation> getJudges(final Connection connection, final int tournament)
        throws SQLException {
    Collection<JudgeInformation> judges = new LinkedList<JudgeInformation>();

    ResultSet rs = null;
    PreparedStatement stmt = null;
    try {
        stmt = connection.prepareStatement("SELECT id, category, station FROM Judges WHERE Tournament = ?");
        stmt.setInt(1, tournament);
        rs = stmt.executeQuery();
        while (rs.next()) {
            final String id = rs.getString(1);
            final String category = rs.getString(2);
            final String station = rs.getString(3);
            final JudgeInformation judge = new JudgeInformation(id, category, station);
            judges.add(judge);
        }
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(stmt);
    }

    return judges;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.DBTestUtil.java

/**
 * Delete all records from the tables specified in tables array. The deletes are executed in
 * the same order as the entries in the tables array.
 *
 * WARNING: This DELETES data and is not undoable. You need to ensure that you are connected to
 * a test database and not a production database.
 *
 * @param tables//from  ww  w . ja va2 s  . c om
 * @param ds
 */
public static void cleanTables(String[] tables, BasicDataSourceConnectionProvider ds) {
    String template = "DELETE FROM %s";
    try {
        Connection connection = ds.getConnection();
        for (String table : tables) {
            String statement = String.format(template, table);
            PreparedStatement preparedStatement = connection.prepareStatement(statement);
            preparedStatement.execute();
        }
    } catch (SQLException e) {

    }
}

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

/**
 * deletes all records from status table for user
 *
 * @param con DB connection object/*www.j a  va 2s  .  c  om*/
 * @param userId user id
 */
private static void deleteAllSystemStatus(Connection con, Long userId) {

    try {

        PreparedStatement stmt = con.prepareStatement("delete from status where user_id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        DBUtils.closeStmt(stmt);

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

}

From source file:cn.edu.zju.acm.onlinejudge.persistence.sql.Database.java

/**
 * Gets the last id./*from w w  w .  jav  a2s.c  o m*/
 * 
 * @param conn
 * @param ps
 * @param rs
 * @return the last id
 * @throws SQLException
 */
public static long getLastId(Connection conn) throws SQLException {
    PreparedStatement ps = null;
    try {
        ps = conn.prepareStatement(Database.GET_LAST_ID);
        ResultSet rs = ps.executeQuery();
        rs.next();
        return rs.getLong(1);
    } finally {
        Database.dispose(ps);
    }
}

From source file:com.chaosinmotion.securechat.server.commands.ForgotPassword.java

/**
 * Process a forgot password request. This generates a token that the
 * client is expected to return with the change password request.
 * @param requestParams/*from  ww  w  .  j av  a2  s  .  c  o m*/
 * @throws SQLException 
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws JSONException 
 * @throws NoSuchAlgorithmException 
 */

public static void processRequest(JSONObject requestParams)
        throws SQLException, ClassNotFoundException, IOException, NoSuchAlgorithmException, JSONException {
    String username = requestParams.optString("username");

    /*
     * Step 1: Convert username to the userid for this
     */
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    int userID = 0;
    String retryID = UUID.randomUUID().toString();

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT userid " + "FROM Users " + "WHERE username = ?");
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next()) {
            userID = rs.getInt(1);
        }

        if (userID == 0)
            return;
        ps.close();
        rs.close();

        /*
         * Step 2: Generate the retry token and insert into the forgot 
         * database with an expiration date 1 hour from now.
         */

        Timestamp ts = new Timestamp(System.currentTimeMillis() + 3600000);
        ps = c.prepareStatement("INSERT INTO ForgotPassword " + "    ( userid, token, expires ) " + "VALUES "
                + "    ( ?, ?, ?)");
        ps.setInt(1, userID);
        ps.setString(2, retryID);
        ps.setTimestamp(3, ts);
        ps.execute();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }

    /*
     * Step 3: formulate a JSON string with the retry and send
     * to the user. The format of the command we send is:
     * 
     * { "cmd": "forgotpassword", "token": token }
     */

    JSONObject obj = new JSONObject();
    obj.put("cmd", "forgotpassword");
    obj.put("token", retryID);
    MessageQueue.getInstance().enqueueAdmin(userID, obj.toString(4));
}

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

/**
 * returns all profile information//from   w  w  w.ja  v a 2s  . c  o m
 *
 * @return list of profiles
 */
public static List<Profile> getAllProfiles() {

    ArrayList<Profile> profileList = new ArrayList<>();
    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement("select * from  profiles order by nm asc");
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            Profile profile = new Profile();
            profile.setId(rs.getLong("id"));
            profile.setNm(rs.getString("nm"));
            profile.setDesc(rs.getString("desc"));
            profileList.add(profile);

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

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

    return profileList;
}