Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Query the database.
- *
- * @param sql
- * The query statement
- * @return List of rows returned by the query.
- */
- public List<Map<String, Object>> query(String sql) {
- return this.query(sql, null);
- }
- /**
- * Query the database.
- *
- * @param sql
- * The query statement
- * @param params
- * The prepared statement parameters (in order).
- * @return List of rows returned by the query.
- */
- public List<Map<String, Object>> query(String sql, Object[] params) {
- final String METHODNAME = "query";
- List<Map<String, Object>> resList = null;
- try {
- if (conn != null && !conn.isClosed()) {
- resList = new ArrayList<Map<String, Object>>();
- PreparedStatement stmt = conn.prepareStatement(sql);
- if (params != null && params.length > 0) {
- for (int i = 1; i <= params.length; i++) { // 1 based, not 0
- stmt.setObject(i, params[i - 1]);
- }
- }
- ResultSet res = stmt.executeQuery(sql);
- while (res.next()) {
- Map<String, Object> row = new HashMap<String, Object>();
- for (int i = 1; i <= res.getMetaData().getColumnCount(); i++) {
- String key = res.getMetaData().getColumnName(i);
- Object val = res.getObject(i);
- row.put(key, val);
- resList.add(row);
- }
- }
- } else {
- logger.log(LogLevel.ALL, CLASSNAME, METHODNAME, "Attempted to run query when "
- + "there was no established connection to the database.");
- }
- } catch (Throwable e) {
- logger.log(LogLevel.ERROR, CLASSNAME, METHODNAME,
- "An error occurred when trying to run the query.");
- }
- return resList;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement