aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio2/com/example/portfolio2/MyDB.java
blob: c7e15ef64e0817eed8cadc152c1da47eda7224f1 (plain)
  1. package com.example.portfolio2;
  2. // origin: <https://moodle.ruc.dk/course/section.php?id=211873>
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.util.ArrayList;
  9. /// standard Database configuration provided at lecture
  10. public class MyDB {
  11. /// foo
  12. Connection conn = null;
  13. /// foo
  14. public MyDB() {
  15. if (conn == null) {
  16. open();
  17. }
  18. }
  19. /// foo
  20. public final void open() {
  21. try {
  22. String url = "jdbc:sqlite:identifier.sqlite";
  23. conn = DriverManager.getConnection(url);
  24. } catch (SQLException e) {
  25. System.out.println("cannot open");
  26. if (conn != null) {
  27. close();
  28. }
  29. throw new RuntimeException(e);
  30. }
  31. }
  32. /// foo
  33. public final void close() {
  34. try {
  35. if (conn != null) {
  36. conn.close();
  37. }
  38. } catch (SQLException e) {
  39. throw new RuntimeException(e);
  40. }
  41. conn = null;
  42. }
  43. /// foo
  44. /// @param sql foo
  45. public final void cmd(final String sql) {
  46. if (conn == null) {
  47. open();
  48. }
  49. if (conn == null) {
  50. System.out.println("No connection");
  51. return;
  52. }
  53. Statement stmt = null;
  54. try {
  55. stmt = conn.createStatement();
  56. stmt.executeUpdate(sql);
  57. } catch (SQLException e) {
  58. System.out.println("Error in statement " + sql);
  59. throw new RuntimeException(e);
  60. }
  61. try {
  62. if (stmt != null) {
  63. stmt.close();
  64. }
  65. } catch (SQLException e) {
  66. System.out.println("Error in statement " + sql);
  67. throw new RuntimeException(e);
  68. }
  69. }
  70. /// foo
  71. /// @param query foo
  72. /// @param fld foo
  73. /// @return foo
  74. public final ArrayList<String> query(
  75. final String query, final String fld
  76. ) {
  77. ArrayList<String> res = new ArrayList<>();
  78. if (conn == null) {
  79. open();
  80. }
  81. if (conn == null) {
  82. System.out.println("No connection");
  83. throw new RuntimeException("No connection");
  84. }
  85. Statement stmt = null;
  86. try {
  87. stmt = conn.createStatement();
  88. ResultSet rs = stmt.executeQuery(query);
  89. while (rs.next()) {
  90. String name = rs.getString(fld);
  91. res.add(name);
  92. }
  93. } catch (SQLException e) {
  94. System.out.println(
  95. "Error in statement "
  96. + query + " " + fld);
  97. throw new RuntimeException(e);
  98. }
  99. try {
  100. if (stmt != null) {
  101. stmt.close();
  102. }
  103. } catch (SQLException e) {
  104. System.out.println(
  105. "Error in statement "
  106. + query + " " + fld);
  107. throw new RuntimeException(e);
  108. }
  109. return res;
  110. }
  111. }