Guest User

Untitled

a guest
Oct 15th, 2017
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. package com.phoenix.controller;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.ResultSetMetaData;
  7. import java.sql.Statement;
  8. import java.util.ArrayList;
  9.  
  10. import org.json.JSONObject;
  11.  
  12. public class DBHelper
  13. {
  14. public static Connection openConnection()
  15. {
  16. try{
  17. Class.forName("com.mysql.jdbc.Driver").newInstance();
  18. Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/CargoTracking","root","123");
  19. return cn;
  20. }
  21. catch(Exception e)
  22. {
  23. System.out.println("[DBhelper:openConnection]:"+e);
  24. return null;
  25. }
  26. }
  27. public static boolean executeUpdate(Connection cn, String query)
  28. {
  29. try
  30. {
  31. Statement smt = cn.createStatement();
  32. smt.executeUpdate(query);
  33. return true;
  34. }
  35. catch(Exception e)
  36. {
  37. System.out.println("[DbHelper:executeUpdate]"+e);
  38. return false;
  39. }
  40. }
  41. public static ResultSet executeQuery(Connection cn, String query)
  42. {
  43. try
  44. {
  45. Statement smt = cn.createStatement();
  46. ResultSet rs = smt.executeQuery(query);
  47. return rs;
  48. }
  49. catch(Exception e)
  50. {
  51. System.out.println("[DBHelper:executeQuery]"+e);
  52. return null;
  53. }
  54. }
  55.  
  56. public static ArrayList<JSONObject> JsonEngine(ResultSet rs)
  57. {
  58. ArrayList<JSONObject> resList = new ArrayList<JSONObject>();
  59. try
  60. {
  61. //Getting column names//
  62. ResultSetMetaData rsMeta = rs.getMetaData();
  63. int columnCount = rsMeta.getColumnCount();
  64. ArrayList<String> columnNames = new ArrayList<String>();
  65. for(int i=1;i<=columnCount;i++)
  66. {
  67. columnNames.add(rsMeta.getColumnName(i).toUpperCase());
  68. }
  69. //Convert the JSON Object to human readable form//
  70. while(rs.next())
  71. {
  72. JSONObject obj = new JSONObject();
  73. for(int i=1;i<=columnCount;i++)
  74. {
  75. String key = columnNames.get(i-1);
  76. String value = rs.getString(i);
  77. obj.put(key,value);
  78. }
  79. resList.add(obj);
  80. }
  81. }
  82. catch(Exception e)
  83. {
  84. e.printStackTrace();
  85. }
  86. finally
  87. {
  88. try
  89. {
  90. rs.close();
  91. }
  92. catch(Exception e)
  93. {
  94. e.printStackTrace();
  95. }
  96.  
  97. }
  98. return resList;
  99.  
  100. }
  101.  
  102. }
Add Comment
Please, Sign In to add comment