Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. /**
  2. * Query the database.
  3. *
  4. * @param sql
  5. * The query statement
  6. * @return List of rows returned by the query.
  7. */
  8. public List<Map<String, Object>> query(String sql) {
  9. return this.query(sql, null);
  10. }
  11.  
  12. /**
  13. * Query the database.
  14. *
  15. * @param sql
  16. * The query statement
  17. * @param params
  18. * The prepared statement parameters (in order).
  19. * @return List of rows returned by the query.
  20. */
  21. public List<Map<String, Object>> query(String sql, Object[] params) {
  22. final String METHODNAME = "query";
  23. List<Map<String, Object>> resList = null;
  24.  
  25. try {
  26. if (conn != null && !conn.isClosed()) {
  27. resList = new ArrayList<Map<String, Object>>();
  28.  
  29. PreparedStatement stmt = conn.prepareStatement(sql);
  30. if (params != null && params.length > 0) {
  31. for (int i = 1; i <= params.length; i++) { // 1 based, not 0
  32. stmt.setObject(i, params[i - 1]);
  33. }
  34. }
  35.  
  36. ResultSet res = stmt.executeQuery(sql);
  37.  
  38. while (res.next()) {
  39. Map<String, Object> row = new HashMap<String, Object>();
  40.  
  41. for (int i = 1; i <= res.getMetaData().getColumnCount(); i++) {
  42. String key = res.getMetaData().getColumnName(i);
  43. Object val = res.getObject(i);
  44. row.put(key, val);
  45. resList.add(row);
  46. }
  47. }
  48.  
  49. } else {
  50. logger.log(LogLevel.ALL, CLASSNAME, METHODNAME, "Attempted to run query when "
  51. + "there was no established connection to the database.");
  52. }
  53. } catch (Throwable e) {
  54. logger.log(LogLevel.ERROR, CLASSNAME, METHODNAME,
  55. "An error occurred when trying to run the query.");
  56. }
  57.  
  58. return resList;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement