diff options
author | Jonas Smedegaard <dr@jones.dk> | 2025-04-28 16:31:25 +0200 |
---|---|---|
committer | Jonas Smedegaard <dr@jones.dk> | 2025-04-28 16:39:21 +0200 |
commit | 9df1ad472f57adecb59768ffe7c847174c86ccc7 (patch) | |
tree | 6b9c460d7ccdd2dcff1f83461e069b68d8678f39 /src/com.example.portfolio2/com/example/portfolio2/MyDb.java | |
parent | 9d419988fa797ca431387db6a77e23832c11c6b3 (diff) |
split classes into separate files
Diffstat (limited to 'src/com.example.portfolio2/com/example/portfolio2/MyDb.java')
-rw-r--r-- | src/com.example.portfolio2/com/example/portfolio2/MyDb.java | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/src/com.example.portfolio2/com/example/portfolio2/MyDb.java b/src/com.example.portfolio2/com/example/portfolio2/MyDb.java new file mode 100644 index 0000000..f85f391 --- /dev/null +++ b/src/com.example.portfolio2/com/example/portfolio2/MyDb.java @@ -0,0 +1,86 @@ +package com.example.portfolio2; + +import java.sql.*; +import java.util.ArrayList; + +class MyDB { // MyDB is all standard Database configuration that was gotten from Mads + Connection conn = null; + + MyDB() { + if (conn == null) open(); + } + + public void open() { + try { + String url = "jdbc:sqlite:identifier.sqlite"; + conn = DriverManager.getConnection(url); + } catch (SQLException e) { + System.out.println("cannot open"); + if (conn != null) close(); + throw new RuntimeException(e); + } + ; + } + + public void close() { + try { + if (conn != null) conn.close(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + conn = null; + } + public void cmd(String sql) { + if (conn == null) open(); + if (conn == null) { + System.out.println("No connection"); + return; + } + Statement stmt = null; + try { + stmt = conn.createStatement(); + stmt.executeUpdate(sql); + } catch (SQLException e) { + System.out.println("Error in statement " + sql); + throw new RuntimeException(e); + } + try { + if (stmt != null) { + stmt.close(); + } + } catch (SQLException e) { + System.out.println("Error in statement " + sql); + throw new RuntimeException(e); + } + } + + public ArrayList<String> query(String query, String fld) { + ArrayList<String> res = new ArrayList<>(); + if (conn == null) open(); + if (conn == null) { + System.out.println("No connection"); + throw new RuntimeException("No connection"); + } + Statement stmt = null; + try { + stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(query); + while (rs.next()) { + String name = rs.getString(fld); + res.add(name); + } + } catch (SQLException e) { + System.out.println("Error in statement " + query + " " + fld); + throw new RuntimeException(e); + } + try { + if (stmt != null) { + stmt.close(); + } + } catch (SQLException e) { + System.out.println("Error in statement " + query + " " + fld); + throw new RuntimeException(e); + } + return res; + } +} |