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