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.data2semantics.yasgui.server.db.ConnectionFactory.java

private static void setDeltaApplied(Connection connect, int deltaId) throws SQLException {
    String sql = "INSERT INTO Deltas (Id) VALUES(?)";
    PreparedStatement statement = connect.prepareStatement(sql);
    statement.setInt(1, deltaId);/*w  ww. j a v  a 2s.c  o m*/
    statement.executeUpdate();
}

From source file:Main.java

public static PreparedStatement createLayersInsertForContextual(Connection conn, int layerId,
        String description, String path, String name, String displayPath, double minLatitude,
        double minLongitude, double maxLatitude, double maxLongitude, String path_orig) throws SQLException {
    PreparedStatement stLayersInsert = conn.prepareStatement(
            "INSERT INTO layers (id, name, description, type, path, displayPath, minlatitude, minlongitude, maxlatitude, maxlongitude, enabled, displayname, uid, path_orig) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
    stLayersInsert.setInt(1, layerId);/*from   w  w  w.  ja va2  s  . com*/
    stLayersInsert.setString(2, name);
    stLayersInsert.setString(3, description);
    stLayersInsert.setString(4, CONTEXTUAL_LAYER_TYPE);
    stLayersInsert.setString(5, path);
    stLayersInsert.setString(6, displayPath);
    stLayersInsert.setDouble(7, minLatitude);
    stLayersInsert.setDouble(8, minLongitude);
    stLayersInsert.setDouble(9, maxLatitude);
    stLayersInsert.setDouble(10, maxLongitude);
    stLayersInsert.setBoolean(11, true);
    stLayersInsert.setString(12, description);
    stLayersInsert.setString(13, Integer.toString(layerId));
    stLayersInsert.setString(14, path_orig);
    return stLayersInsert;
}

From source file:org.red5.webapps.admin.controllers.service.UserDAO.java

public static boolean addUser(String username, String hashedPassword) {
    boolean result = false;

    Connection conn = null;
    PreparedStatement stmt = null;
    try {//from   www.j ava  2s  .c  o m
        conn = UserDatabase.getConnection();
        //make a statement
        stmt = conn
                .prepareStatement("INSERT INTO APPUSER (username, password, enabled) VALUES (?, ?, 'enabled')");
        stmt.setString(1, username);
        stmt.setString(2, hashedPassword);
        log.debug("Add user: {}", stmt.execute());
        //add role
        stmt = conn.prepareStatement("INSERT INTO APPROLE (username, authority) VALUES (?, 'ROLE_SUPERVISOR')");
        stmt.setString(1, username);
        log.debug("Add role: {}", stmt.execute());
        //
        result = true;
    } catch (Exception e) {
        log.error("Error connecting to db", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            UserDatabase.recycle(conn);
        }
    }
    return result;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.db.TopicDaoImplTest.java

@AfterClass
public static void cleanupDatabase() throws Exception {
    final String statementStr1 = "DELETE FROM ofPubsubNode WHERE nodeID LIKE '%" + NODE_PREFIX + "%'";

    Connection conn = null;
    PreparedStatement pstmt1 = null;

    try {// ww w.  ja  v a2s  . c o  m
        conn = UnitTestDSProvider.getDataSource().getConnection();
        pstmt1 = conn.prepareStatement(statementStr1);
        pstmt1.execute();
    } catch (SQLException e) {
        LOGGER.error("cleanupDatabase : {}", e);
    } finally {
        CloseUtil.close(LOGGER, pstmt1, conn);
    }
}

From source file:com.sql.DocketNotification.java

/**
 * Gather a list of notifications for items that were docketed
 * /*from   ww w  . j a  v  a2  s . c  o  m*/
 * @return
 */
public static List<DocketNotificationModel> getQueuedNotifications() {
    List<DocketNotificationModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM DocketNotifications";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            DocketNotificationModel item = new DocketNotificationModel();
            item.setId(rs.getInt("id"));
            item.setSection(rs.getString("Section"));
            item.setSendTo(rs.getString("sendTo"));
            item.setMessageSubject(rs.getString("emailSubject"));
            item.setMessageBody(rs.getString("emailBody"));
            list.add(item);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:ch.newscron.referral.ReferralManager.java

/**
 * Given a customer id and a generated short URL, inserts these two as a new row in the ShortURL table of the database
 * @param customerId an long representing the unique customer id
 * @param shortURL a String representing the short goo.gl generated URL
 *//*from   w w  w .  j  ava2  s.  c  om*/
public static boolean insertShortURL(long customerId, String shortURL) {
    Connection connection = null;
    PreparedStatement query = null;
    try {
        connection = connect();
        query = connection.prepareStatement("INSERT IGNORE INTO ShortURL (custId, shortUrl) VALUES(?, ?)");
        query.setLong(1, customerId);
        query.setString(2, shortURL);
        int newShortURL = query.executeUpdate();
        return newShortURL == 1;
    } catch (Exception ex) {
        Logger.getLogger(ReferralManager.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        disconnect(connection, query);
    }
    return false;
}

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

public static long deleteRaterRating(Connection con, RaterRatingPK pk) throws SQLException {
    PreparedStatement prepStmt = con.prepareStatement(QUERY_DELETE_RATER_RATING);
    try {/*from   w ww . j  a v a 2s .  c o m*/
        prepStmt.setString(1, pk.getInstanceId());
        prepStmt.setString(2, pk.getContributionId());
        prepStmt.setString(3, pk.getContributionType());
        prepStmt.setString(4, pk.getRater().getId());
        return prepStmt.executeUpdate();
    } finally {
        DBUtil.close(prepStmt);
    }
}

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

public static boolean existRaterRating(Connection con, RaterRatingPK pk) throws SQLException {
    PreparedStatement prepStmt = con.prepareStatement(QUERY_EXISTS_RATER_RATING);
    prepStmt.setString(1, pk.getInstanceId());
    prepStmt.setString(2, pk.getContributionId());
    prepStmt.setString(3, pk.getContributionType());
    prepStmt.setString(4, pk.getRater().getId());
    ResultSet rs = null;//w  w w . ja  v a 2s.  c  om

    try {
        rs = prepStmt.executeQuery();
        return (rs.next());
    } finally {
        DBUtil.close(rs, prepStmt);
    }
}

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

public static void processRequest(UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    ArrayList<Message> messages = new ArrayList<Message>();

    JSONArray a = requestParams.getJSONArray("messages");
    int i, len = a.length();
    for (i = 0; i < len; ++i) {
        JSONObject item = a.getJSONObject(i);
        Message msg = new Message();
        msg.message = item.getInt("messageid");
        msg.checksum = item.getString("checksum");
        messages.add(msg);//from w  w w  .  ja va2  s  .  co m
    }

    /*
     * Iterate through the messages, deleting each. We only delete a
     * message if message belongs to the user and the checksum matches.
     * This assumes it's our message and it was read with someone who
     * can read the message.
     * 
     * (Thus, the weird query)
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        int count = 0;
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN "
                + "    (SELECT Messages.messageid " + "     FROM Messages, Devices "
                + "     WHERE Messages.messageid = ? " + "     AND Messages.checksum = ? "
                + "     AND Devices.deviceid = Messages.deviceid " + "     AND Devices.userid = ?)");

        for (Message msg : messages) {
            /*
             * Get the device ID for this device. Verify it belongs to the
             * user specified
             */

            ps.setInt(1, msg.message);
            ps.setString(2, msg.checksum);
            ps.setInt(3, userinfo.getUserID());
            ps.addBatch();
            ++count;
            if (count > 10240) {
                ps.executeBatch();
            }
        }
        if (count > 0) {
            ps.executeBatch();
        }
    } catch (BatchUpdateException batch) {
        throw batch.getNextException();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:ch.newscron.registration.UserRegistration.java

public static List<User> getAllUsers() {
    Connection connection = null;
    PreparedStatement query = null;
    ResultSet rs = null;/*ww w .jav a  2  s . co m*/
    try {
        connection = connect();
        query = connection.prepareStatement("SELECT * FROM ShortURL, User WHERE User.campaignId=ShortURL.id");
        rs = query.executeQuery();
        List<User> userList = parseResultSet(rs);

        return userList;
    } catch (Exception ex) {
        Logger.getLogger(UserRegistration.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        disconnect(connection, query, rs);
    }
    return null;
}