aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio2/com/example/portfolio2/MyDB.java
blob: 4eb07f4b53818dfa8e032571b76f9a003d411183 (plain)
  1. package com.example.portfolio2;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. /// standard Database configuration provided at lecture
  9. public class MyDB {
  10. /// foo
  11. Connection conn = null;
  12. /// foo
  13. MyDB() {
  14. if (conn == null) open();
  15. }
  16. /// foo
  17. public void open() {
  18. try {
  19. String url = "jdbc:sqlite:identifier.sqlite";
  20. conn = DriverManager.getConnection(url);
  21. } catch (SQLException e) {
  22. System.out.println("cannot open");
  23. if (conn != null) close();
  24. throw new RuntimeException(e);
  25. }
  26. ;
  27. }
  28. /// foo
  29. public void close() {
  30. try {
  31. if (conn != null) conn.close();
  32. } catch (SQLException e) {
  33. throw new RuntimeException(e);
  34. }
  35. conn = null;
  36. }
  37. /// foo
  38. /// @param sql foo
  39. public void cmd(String sql) {
  40. if (conn == null) open();
  41. if (conn == null) {
  42. System.out.println("No connection");
  43. return;
  44. }
  45. Statement stmt = null;
  46. try {
  47. stmt = conn.createStatement();
  48. stmt.executeUpdate(sql);
  49. } catch (SQLException e) {
  50. System.out.println("Error in statement " + sql);
  51. throw new RuntimeException(e);
  52. }
  53. try {
  54. if (stmt != null) {
  55. stmt.close();
  56. }
  57. } catch (SQLException e) {
  58. System.out.println("Error in statement " + sql);
  59. throw new RuntimeException(e);
  60. }
  61. }
  62. /// foo
  63. /// @param query foo
  64. /// @param fld foo
  65. /// @return foo
  66. public ArrayList<String> query(String query, String fld) {
  67. ArrayList<String> res = new ArrayList<>();
  68. if (conn == null) open();
  69. if (conn == null) {
  70. System.out.println("No connection");
  71. throw new RuntimeException("No connection");
  72. }
  73. Statement stmt = null;
  74. try {
  75. stmt = conn.createStatement();
  76. ResultSet rs = stmt.executeQuery(query);
  77. while (rs.next()) {
  78. String name = rs.getString(fld);
  79. res.add(name);
  80. }
  81. } catch (SQLException e) {
  82. System.out.println("Error in statement " + query + " " + fld);
  83. throw new RuntimeException(e);
  84. }
  85. try {
  86. if (stmt != null) {
  87. stmt.close();
  88. }
  89. } catch (SQLException e) {
  90. System.out.println("Error in statement " + query + " " + fld);
  91. throw new RuntimeException(e);
  92. }
  93. return res;
  94. }
  95. }