aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio2/com/example/portfolio2/MyDb.java
blob: 78d08f06fd366fa0291b342de8ec39064a4cd647 (plain)
  1. // SPDX-FileCopyrightText: <Alexander Marthin Klemensen stud-marthin@ruc.dk>
  2. // SPDX-FileCopyrightText: <Ian Valentin Christensen stud-ianc@ruc.dk>
  3. // SPDX-FileCopyrightText: <Zahed Noos zahed@ruc.dk>
  4. package com.example.portfolio2;
  5. import java.sql.*;
  6. import java.util.ArrayList;
  7. class MyDB { // MyDB is all standard Database configuration that was gotten from Mads
  8. Connection conn = null;
  9. MyDB() {
  10. if (conn == null) open();
  11. }
  12. public void open() {
  13. try {
  14. String url = "jdbc:sqlite:identifier.sqlite";
  15. conn = DriverManager.getConnection(url);
  16. } catch (SQLException e) {
  17. System.out.println("cannot open");
  18. if (conn != null) close();
  19. throw new RuntimeException(e);
  20. }
  21. ;
  22. }
  23. public void close() {
  24. try {
  25. if (conn != null) conn.close();
  26. } catch (SQLException e) {
  27. throw new RuntimeException(e);
  28. }
  29. conn = null;
  30. }
  31. public void cmd(String sql) {
  32. if (conn == null) open();
  33. if (conn == null) {
  34. System.out.println("No connection");
  35. return;
  36. }
  37. Statement stmt = null;
  38. try {
  39. stmt = conn.createStatement();
  40. stmt.executeUpdate(sql);
  41. } catch (SQLException e) {
  42. System.out.println("Error in statement " + sql);
  43. throw new RuntimeException(e);
  44. }
  45. try {
  46. if (stmt != null) {
  47. stmt.close();
  48. }
  49. } catch (SQLException e) {
  50. System.out.println("Error in statement " + sql);
  51. throw new RuntimeException(e);
  52. }
  53. }
  54. public ArrayList<String> query(String query, String fld) {
  55. ArrayList<String> res = new ArrayList<>();
  56. if (conn == null) open();
  57. if (conn == null) {
  58. System.out.println("No connection");
  59. throw new RuntimeException("No connection");
  60. }
  61. Statement stmt = null;
  62. try {
  63. stmt = conn.createStatement();
  64. ResultSet rs = stmt.executeQuery(query);
  65. while (rs.next()) {
  66. String name = rs.getString(fld);
  67. res.add(name);
  68. }
  69. } catch (SQLException e) {
  70. System.out.println("Error in statement " + query + " " + fld);
  71. throw new RuntimeException(e);
  72. }
  73. try {
  74. if (stmt != null) {
  75. stmt.close();
  76. }
  77. } catch (SQLException e) {
  78. System.out.println("Error in statement " + query + " " + fld);
  79. throw new RuntimeException(e);
  80. }
  81. return res;
  82. }
  83. }