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