summaryrefslogtreecommitdiff
path: root/src/com.example.portfolio2/com/example/portfolio2/MyDb.java
blob: 895d7f58d82c7ccd708c29bd0db4c5cfa624eca2 (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. // SPDX-License-Identifier: GPL-3.0-or-later
  5. package com.example.portfolio2;
  6. import java.sql.Connection;
  7. import java.sql.DriverManager;
  8. import java.sql.ResultSet;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11. import java.util.ArrayList;
  12. class MyDB { // MyDB is all standard Database configuration that was gotten from Mads
  13. Connection conn = null;
  14. MyDB() {
  15. if (conn == null) open();
  16. }
  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. public void close() {
  29. try {
  30. if (conn != null) conn.close();
  31. } catch (SQLException e) {
  32. throw new RuntimeException(e);
  33. }
  34. conn = null;
  35. }
  36. public void cmd(String sql) {
  37. if (conn == null) open();
  38. if (conn == null) {
  39. System.out.println("No connection");
  40. return;
  41. }
  42. Statement stmt = null;
  43. try {
  44. stmt = conn.createStatement();
  45. stmt.executeUpdate(sql);
  46. } catch (SQLException e) {
  47. System.out.println("Error in statement " + sql);
  48. throw new RuntimeException(e);
  49. }
  50. try {
  51. if (stmt != null) {
  52. stmt.close();
  53. }
  54. } catch (SQLException e) {
  55. System.out.println("Error in statement " + sql);
  56. throw new RuntimeException(e);
  57. }
  58. }
  59. public ArrayList<String> query(String query, String fld) {
  60. ArrayList<String> res = new ArrayList<>();
  61. if (conn == null) open();
  62. if (conn == null) {
  63. System.out.println("No connection");
  64. throw new RuntimeException("No connection");
  65. }
  66. Statement stmt = null;
  67. try {
  68. stmt = conn.createStatement();
  69. ResultSet rs = stmt.executeQuery(query);
  70. while (rs.next()) {
  71. String name = rs.getString(fld);
  72. res.add(name);
  73. }
  74. } catch (SQLException e) {
  75. System.out.println("Error in statement " + query + " " + fld);
  76. throw new RuntimeException(e);
  77. }
  78. try {
  79. if (stmt != null) {
  80. stmt.close();
  81. }
  82. } catch (SQLException e) {
  83. System.out.println("Error in statement " + query + " " + fld);
  84. throw new RuntimeException(e);
  85. }
  86. return res;
  87. }
  88. }