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