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