List of usage examples for java.sql PreparedStatement getResultSet
ResultSet getResultSet() throws SQLException;
ResultSet
object. From source file:com.l2jserver.model.template.NPCTemplateConverter.java
private static Droplist fillDropList(final ObjectFactory factory, ResultSet npcRs, int npcId) throws SQLException { final Connection conn = npcRs.getStatement().getConnection(); final Droplist drops = factory.createNPCTemplateDroplist(); final PreparedStatement st = conn.prepareStatement("SELECT * FROM droplist WHERE mobId = ?"); st.setInt(1, npcId);//from www. j ava 2 s . c o m st.execute(); final ResultSet rs = st.getResultSet(); while (rs.next()) { final Droplist.Item item = factory.createNPCTemplateDroplistItem(); item.setId(new ItemTemplateID(rs.getInt("itemId"), null)); item.setMin(rs.getInt("min")); item.setMax(rs.getInt("max")); item.setChance(rs.getInt("chance")); item.setCategory(getCategory(rs.getInt("category"))); drops.getItem().add(item); } if (drops.getItem().size() == 0) return null; return drops; }
From source file:com.dynamobi.network.DynamoNetworkUdr.java
/** * Grabbing the list of repos along with their availability * status for internal use. /* w w w . j av a2s. c o m*/ */ private static List<RepoInfo> getRepoUrls() throws SQLException { List<RepoInfo> repos = new ArrayList<RepoInfo>(); Connection conn = DriverManager.getConnection("jdbc:default:connection"); String query = "SELECT repo_url FROM localdb.sys_network.repositories " + "ORDER BY repo_url"; PreparedStatement ps = conn.prepareStatement(query); ps.execute(); ResultSet rs = ps.getResultSet(); while (rs.next()) { String repo = rs.getString(1); boolean accessible = true; try { JSONObject ob = downloadMetadata(repo); } catch (SQLException e) { if (e.getMessage().equals(URL_TIMEOUT)) accessible = false; } repos.add(new RepoInfo(repo, accessible)); } rs.close(); ps.close(); return repos; }
From source file:com.chaosinmotion.securechat.server.commands.CreateAccount.java
/** * Process the create account request. This should receive the following * objects: the username, the password, the device ID and the public key * for the device. This adds a new entry in the account database, and * creates a new device.//from ww w . ja v a 2 s. c o m * * If the user account cannot be created, this returns nil. * @param requestParams * @return */ public static UserInfo processRequest(JSONObject requestParams) throws ClassNotFoundException, SQLException, IOException { String username = requestParams.optString("username"); String password = requestParams.optString("password"); String deviceid = requestParams.optString("deviceid"); String pubkey = requestParams.optString("pubkey"); /* * Attempt to insert a new user into the database */ Connection c = null; PreparedStatement ps = null; ResultSet rs = null; try { c = Database.get(); ps = c.prepareStatement("INSERT INTO Users " + " ( username, password ) " + "VALUES " + " ( ?, ? ); SELECT currval('Users_userid_seq')"); ps.setString(1, username); ps.setString(2, password); try { ps.execute(); } catch (SQLException ex) { return null; // Can't insert; duplicate username? } int utc = ps.getUpdateCount(); int userid = 0; if ((utc == 1) && ps.getMoreResults()) { rs = ps.getResultSet(); if (rs.next()) { userid = rs.getInt(1); } rs.close(); rs = null; } ps.close(); ps = null; /* * We now have the user index. Insert the device. Note that it is * highly unlikely we will have a UUID collision, but we verify * we don't by deleting any rows in the device table with the * specified UUID. The worse case scenario is a collision which * knocks someone else off the air. (The alternative would be * to accidentally send the wrong person duplicate messages.) * * Note that we don't actually use a device-identifying identifer, * choosing instead to pick a UUID, so we need to deal with * the possibility (however remote) of duplicate UUIDs. * * In the off chance we did have a collision, we also delete all * old messages to the device; that prevents messages from being * accidentally delivered. */ ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN " + " (SELECT Messages.messageid " + " FROM Messages, Devices " + " WHERE Messages.deviceid = Devices.deviceid " + " AND Devices.deviceuuid = ?)"); ps.setString(1, deviceid); ps.execute(); ps.close(); ps = null; ps = c.prepareStatement("DELETE FROM Devices WHERE deviceuuid = ?"); ps.setString(1, deviceid); ps.execute(); ps.close(); ps = null; ps = c.prepareStatement("INSERT INTO Devices " + " ( userid, deviceuuid, publickey ) " + "VALUES " + " ( ?, ?, ?)"); ps.setInt(1, userid); ps.setString(2, deviceid); ps.setString(3, pubkey); ps.execute(); /* * Complete; return the user info record */ return new Login.UserInfo(userid); } finally { if (rs != null) rs.close(); if (ps != null) ps.close(); if (c != null) c.close(); } }
From source file:edu.ucsb.nceas.MCTestCase.java
protected static Vector<Hashtable<String, Object>> dbSelect(String sqlStatement, String methodName) throws SQLException { Vector<Hashtable<String, Object>> resultVector = new Vector<Hashtable<String, Object>>(); DBConnectionPool connPool = DBConnectionPool.getInstance(); DBConnection dbconn = DBConnectionPool.getDBConnection(methodName); int serialNumber = dbconn.getCheckOutSerialNumber(); PreparedStatement pstmt = null; debug("Selecting from db: " + sqlStatement); pstmt = dbconn.prepareStatement(sqlStatement); pstmt.execute();//from w w w .j ava 2 s .c om ResultSet resultSet = pstmt.getResultSet(); ResultSetMetaData rsMetaData = resultSet.getMetaData(); int numColumns = rsMetaData.getColumnCount(); debug("Number of data columns: " + numColumns); while (resultSet.next()) { Hashtable<String, Object> hashTable = new Hashtable<String, Object>(); for (int i = 1; i <= numColumns; i++) { if (resultSet.getObject(i) != null) { hashTable.put(rsMetaData.getColumnName(i), resultSet.getObject(i)); } } debug("adding data row to result vector"); resultVector.add(hashTable); } resultSet.close(); pstmt.close(); DBConnectionPool.returnDBConnection(dbconn, serialNumber); return resultVector; }
From source file:org.openmrs.web.filter.util.FilterUtil.java
/** * Tries to retrieve location parameter. First this method makes an attempt to load locale * parameter as user's property. And next, if user's property is empty it tries to retrieve * default system locale (i.e system global property). If it also is empty it uses default value * for system locale//from www. j a va2 s . c o m * * @param username the name of the administrative user whose default locale property will be * restored * @return string with stored location parameter or default OpenMRS locale property's value */ public static String restoreLocale(String username) { String currentLocale = null; if (StringUtils.isNotBlank(username)) { PreparedStatement statement = null; Connection connection = null; try { connection = DatabaseUpdater.getConnection(); // first we should try to get locale parameter as user's property Integer userId = getUserIdByName(username, connection); if (userId != null) { String select = "select property_value from user_property where user_id = ? and property = ?"; statement = connection.prepareStatement(select); statement.setInt(1, userId); statement.setString(2, OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE); if (statement.execute()) { ResultSet results = statement.getResultSet(); if (results.next()) { currentLocale = results.getString(1); } } //close statement statement.close(); } // if locale is still null we should try to retrieve system locale global property's value if (currentLocale == null) { currentLocale = readSystemDefaultLocale(connection); } } catch (Exception e) { log.error("Error while retriving locale property", e); } finally { try { if (statement != null && !statement.isClosed()) { statement.close(); } } catch (SQLException e) { log.warn("Error while closing statement"); } if (connection != null) { try { connection.close(); } catch (SQLException e) { log.debug("Error while closing the database", e); } } } } // if locale is still null we just simply using default locale value (i.e. en_GB) if (currentLocale == null) { currentLocale = OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE; } return currentLocale; }
From source file:net.mindengine.oculus.frontend.db.jdbc.MySimpleJdbcDaoSupport.java
public Long queryForLong(String sql) throws Exception { logQuery(sql, null);//from w w w. j a va 2s . c om PreparedStatement ps = getConnection().prepareStatement(sql); ps.execute(); ResultSet rs = ps.getResultSet(); if (rs.next()) { return rs.getLong(1); } return null; }
From source file:net.mindengine.oculus.frontend.db.jdbc.MySimpleJdbcDaoSupport.java
/** * Returns a collection of string values * @param sql//from ww w. j a v a 2s . c o m * @return * @throws Exception */ public Collection<String> queryStrings(String sql) throws Exception { PreparedStatement ps = getConnection().prepareStatement(sql); logger.info(ps); ps.execute(); ResultSet rs = ps.getResultSet(); Collection<String> results = new LinkedList<String>(); while (rs.next()) { results.add(rs.getString(1)); } return results; }
From source file:hu.petabyte.redflags.engine.gear.indicator.helper.KMonitorInstitutions.java
public void init() { if (initialized) { return;//from www .jav a2 s.c om } if (null == dbhost || null == dbname || null == dbuser || null == dbpass) { LOG.warn("K-Monitor Institutions component is not initialized."); return; } try { LOG.info("Connecting to K-Monitor database..."); conn = DriverManager.getConnection( String.format("jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=utf-8", dbhost, dbname), dbuser, dbpass); LOG.info("Querying institutions..."); PreparedStatement ps = conn.prepareStatement("SELECT name FROM news_institutions"); ps.execute(); ResultSet rs = ps.getResultSet(); while (rs.next()) { institutions.add(rs.getString(1)); } rs.close(); ps.close(); LOG.info("We have {} institutions", institutions.size()); conn.close(); } catch (Exception e) { LOG.error("Failed to connect to KMDB.", e); } initialized = true; }
From source file:com.haulmont.cuba.core.app.NumberIdWorker.java
protected Object executeScript(String entityName, String sqlScript) { EntityManager em = persistence.getEntityManager(getDataStore(entityName)); StrTokenizer tokenizer = new StrTokenizer(sqlScript, SequenceSupport.SQL_DELIMITER); Object value = null;//from w w w . j a v a 2 s .c o m Connection connection = em.getConnection(); while (tokenizer.hasNext()) { String sql = tokenizer.nextToken(); try { PreparedStatement statement = connection.prepareStatement(sql); try { if (statement.execute()) { ResultSet rs = statement.getResultSet(); if (rs.next()) value = rs.getLong(1); } } finally { DbUtils.closeQuietly(statement); } } catch (SQLException e) { throw new IllegalStateException("Error executing SQL for getting next number", e); } } return value; }
From source file:de.ingrid.iplug.dsc.index.mapper.DatabaseProfileMapper.java
@Override public void map(SourceRecord record, ElasticDocument doc) { if (!(record instanceof DatabaseSourceRecord)) { throw new IllegalArgumentException("Record is no DatabaseRecord!"); }// w w w . j av a2 s. c o m Connection connection = (Connection) record.get(DatabaseSourceRecord.CONNECTION); try { String docId = (String) record.get(DatabaseSourceRecord.ID); ResultSet rs = connection .prepareStatement("SELECT value_string FROM sys_generic_key WHERE key_name='PROFILE'") .getResultSet(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); InputSource source = new InputSource(new StringReader(rs.getString(0))); org.w3c.dom.Document document = factory.newDocumentBuilder().parse(source); rs.close(); NodeList nl = xPathUtils.getNodeList(document, "/PATH_TO_ADDITIONAL_FIELDS"); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); String dbName = xPathUtils.getString(n, "/XPATH_TO_DB_FIELD_NAME"); String idxName = xPathUtils.getString(n, "/XPATH_TO_INDEX_FIELD_NAME"); PreparedStatement ps = connection .prepareStatement("SELECT value FROM additional_fields WHERE key_name='" + dbName + "' AND WHERE doc_id='" + docId + "'"); rs = ps.getResultSet(); String value = rs.getString(0); rs.close(); ps.close(); doc.put(idxName, value); } } catch (Exception e) { log.error("Error mapping profile data.", e); } }