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.webbfontaine.valuewebb.gtns.TTGTNSSynchronizer.java

private static void updateTTFlag(TtGen ttGen) {
    Connection conn = null;
    PreparedStatement ps = null;//from w  w  w .ja  va2s  . c  o  m
    try {
        conn = Utils.getSQLConnection();
        conn.setAutoCommit(false);
        ps = conn.prepareStatement(UPDATE_TT_SQL);
        ps.setLong(1, ttGen.getId());
        ps.executeUpdate();
        conn.commit();
    } catch (SQLException e) {
        LOGGER.error("Error in updating GCNet Submission Flag for TT with id {0}, error {1}", ttGen.getId(), e);
    } finally {
        DBUtils.closeResource(ps);
        DBUtils.closeResource(conn);
    }
}

From source file:com.wso2telco.util.DbUtil.java

public static String getContextIDForHashKey(String hashKey) throws AuthenticatorException, SQLException {
    String sessionDataKey = null;

    String sql = "select contextid from sms_hashkey_contextid_mapping where hashkey=?";

    Connection connection = null;
    PreparedStatement ps = null;//from   www .  j  a  v a  2  s. c o  m
    ResultSet rs = null;
    try {
        connection = getConnectDBConnection();
        ps = connection.prepareStatement(sql);
        ps.setString(1, hashKey);
        rs = ps.executeQuery();
        while (rs.next()) {
            sessionDataKey = rs.getString("contextid");
        }
    } catch (SQLException e) {
        handleException(e.getMessage(), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rs, ps);
    }
    return sessionDataKey;
}

From source file:com.dynamobi.ws.util.DB.java

@SuppressWarnings(value = { "unchecked" })
public static <T extends DBLoader> void execute(String query, T obj, List<T> list) {
    Connection conn = null;
    PreparedStatement ps = null;/* www. j av a  2 s .co m*/
    ResultSet rs = null;

    try {
        conn = getConnection();
        ps = conn.prepareStatement(query);
        ps.setMaxRows(0);
        if (ps.execute()) {
            rs = ps.getResultSet();
        }

        while (rs != null && rs.next()) {
            obj.loadRow(rs);
            if (list != null) {
                list.add((T) obj.copy());
            }
        }
        obj.finalize();
    } catch (SQLException ex) {
        obj.exception(ex);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (conn != null) {
            releaseConnection();
        }
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException ex1) {
            ex1.printStackTrace();
        }
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex3) {
            ex3.printStackTrace();
        }
    }
}

From source file:com.wso2telco.util.DbUtil.java

public static String updateRegistrationStatus(String uuid, String status)
        throws SQLException, AuthenticatorException {

    Connection connection;
    PreparedStatement ps;/*w w  w.  j a v a2 s.com*/
    String sql = "UPDATE regstatus SET status = ? WHERE uuid = ?;";
    connection = getConnectDBConnection();
    ps = connection.prepareStatement(sql);
    ps.setString(1, status);
    ps.setString(2, uuid);
    log.info(ps.toString());
    ps.execute();

    if (connection != null) {
        connection.close();
    }
    return uuid;
}

From source file:org.red5.server.plugin.admin.dao.UserDAO.java

public static UserDetails getUser(String username) {
    UserDetails details = null;//from   w  w w  .  j  a  v  a  2  s  .com
    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        // JDBC stuff
        DataSource ds = UserDatabase.getDataSource();

        conn = ds.getConnection();
        //make a statement
        stmt = conn.prepareStatement("SELECT * FROM APPUSER WHERE username = ?");
        stmt.setString(1, username);
        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            log.debug("User found");
            details = new UserDetails();
            details.setEnabled("enabled".equals(rs.getString("enabled")));
            details.setPassword(rs.getString("password"));
            details.setUserid(rs.getInt("userid"));
            details.setUsername(rs.getString("username"));
            //
            rs.close();
            //get role            
            stmt = conn.prepareStatement("SELECT authority FROM APPROLE WHERE username = ?");
            stmt.setString(1, username);
            rs = stmt.executeQuery();
            if (rs.next()) {
                Collection<? extends GrantedAuthority> authorities;
                //                  authorities.addAll((Collection<?>) new GrantedAuthorityImpl(rs.getString("authority")));
                //                  details.setAuthorities(authorities);
                //
                //if (daoAuthenticationProvider != null) {
                //User usr = new User(username, details.getPassword(), true, true, true, true, authorities);
                //daoAuthenticationProvider.getUserCache().putUserInCache(usr);               
                //}
            }
        }
        rs.close();
    } catch (Exception e) {
        log.error("Error connecting to db", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
    return details;
}

From source file:com.linkedin.databus.bootstrap.utils.BootstrapDBCleanerMain.java

private static List<String> getSourceNames(Connection conn) throws SQLException {
    List<String> srcNames = new ArrayList<String>();
    String sql = "select src from bootstrap_sources";
    ResultSet rs = null;/*from  ww  w  .j  a  v a 2s  .  c om*/
    PreparedStatement stmt = null;
    try {
        stmt = conn.prepareStatement(sql);
        rs = stmt.executeQuery();

        while (rs.next()) {
            String name = rs.getString(1);
            srcNames.add(name);
        }
    } finally {
        DBHelper.close(rs, stmt, null);
    }

    return srcNames;
}

From source file:dsd.dao.DAOProvider.java

/**
 * the delete row function done in a secure way
 * /*from   ww  w  . j  a va  2 s.c  o  m*/
 * @param table
 * @param where
 * @param con
 * @return
 * @throws SQLException
 */
public static int DeleteRowSecure(String table, String where, Connection con, Object[] parameters)
        throws SQLException {
    try {
        PreparedStatement command = con.prepareStatement(
                String.format("delete from %s %s", table, (where.trim().equals("") ? "" : "where " + where)));

        if (parameters != null) {
            for (int i = 0; i < parameters.length; i++) {
                SetParameter(command, parameters[i], i + 1);
            }
        }

        return command.executeUpdate();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return 0;
}

From source file:com.example.querybuilder.server.Jdbc.java

public static PreparedStatement prepareStatement(Connection connection, String sql) {
    try {/*from  w  ww. ja  va2 s  .c o  m*/
        return connection.prepareStatement(sql);
    } catch (SQLException e) {
        throw new SqlRuntimeException(e.toString() + "\n" + sql);
    }
}

From source file:io.hops.metadata.ndb.mysqlserver.MysqlServerConnector.java

public static void truncateTable(boolean transactional, String tableName, int limit)
        throws StorageException, SQLException {
    MysqlServerConnector connector = MysqlServerConnector.getInstance();
    try {/* w  w  w . j  a  v a2s  . c om*/
        Connection conn = connector.obtainSession();
        if (transactional) {
            if (limit > 0) {
                PreparedStatement s = conn.prepareStatement("delete from " + tableName + " limit " + limit);
                s.executeUpdate();
            } else {
                int nbrows = 0;
                do {
                    PreparedStatement s = conn.prepareStatement("delete from " + tableName + " limit 1000");
                    nbrows = s.executeUpdate();
                } while (nbrows > 0);
            }
        } else {
            PreparedStatement s = conn.prepareStatement("truncate table " + tableName);
            s.executeUpdate();
        }
    } finally {
        connector.closeSession();
    }
}

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

public static ReturnResult processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String deviceid = requestParams.optString("deviceid");
    MessageReturnResult mrr = new MessageReturnResult();

    /*/*  w ww.  jav  a2 s  .  c om*/
     * Save message to the database.
     */

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

    try {
        /*
         * Get the device ID for this device. Verify it belongs to the
         * user specified
         */
        c = Database.get();
        ps = c.prepareStatement("SELECT deviceid " + "FROM Devices " + "WHERE deviceuuid = ? AND userid = ?");
        ps.setString(1, deviceid);
        ps.setInt(2, userinfo.getUserID());
        rs = ps.executeQuery();

        int deviceID = 0;
        if (rs.next()) {
            deviceID = rs.getInt(1);
        }

        rs.close();
        ps.close();
        if (deviceID == 0) {
            return new ReturnResult(Errors.ERROR_UNKNOWNDEVICE, "Unknown device");
        }

        /*
         * Run query to get messages
         */

        ps = c.prepareStatement("SELECT Messages.messageid, " + "    Messages.senderid, "
                + "    Users.username, " + "    Messages.toflag, " + "    Messages.received, "
                + "    Messages.message " + "FROM Messages, Users " + "WHERE Messages.deviceid = ? "
                + "  AND Messages.senderid = Users.userid");
        ps.setInt(1, deviceID);

        rs = ps.executeQuery();
        while (rs.next()) {
            int messageID = rs.getInt(1);
            int senderID = rs.getInt(2);
            String senderName = rs.getString(3);
            boolean toflag = rs.getBoolean(4);
            Timestamp received = rs.getTimestamp(5);
            byte[] message = rs.getBytes(6);

            mrr.addMessage(messageID, senderID, senderName, toflag, received, message);
        }

        /*
         * Return messages
         */
        return mrr;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}