moved dbconnection to own class
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package com.bib.essensbestellungsverwaltung;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
public class Database {
|
||||
private static final String dbLocation = "jdbc:sqlite:"+Database.class.getResource("database/database.db");
|
||||
protected static Connection connect(){
|
||||
Connection conn = null;
|
||||
try{
|
||||
conn = DriverManager.getConnection(dbLocation);
|
||||
}catch (SQLException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
protected static void createDb(){
|
||||
String sql = """
|
||||
CREATE TABLE IF NOT EXISTS user (
|
||||
id integer PRIMARY KEY,
|
||||
name text);""";
|
||||
try(Connection conn = connect(); Statement stmt = conn.createStatement()){
|
||||
stmt.execute(sql);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected static void fillSampleDb(){
|
||||
String sql = """
|
||||
INSERT INTO user (id,name)
|
||||
VALUES (1,'test1');""";
|
||||
try(Connection conn = connect(); Statement stmt = conn.createStatement()){
|
||||
stmt.execute(sql);
|
||||
}catch (SQLException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected static void printSampleQuery(){
|
||||
String sql = """
|
||||
SELECT * FROM user WHERE id > ?;""";
|
||||
try(Connection conn = connect()){
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql);
|
||||
pstmt.setInt(1,0);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
while (rs.next()){
|
||||
System.out.println(rs.getInt("id"));
|
||||
System.out.println(rs.getString("name"));
|
||||
}
|
||||
}catch (SQLException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected static void deleteSample(){
|
||||
String sql = """
|
||||
DELETE FROM user WHERE id = ?;""";
|
||||
try(Connection conn = connect();PreparedStatement pstmt = conn.prepareStatement(sql)){
|
||||
pstmt.setInt(1,1);
|
||||
pstmt.executeUpdate();
|
||||
}catch (SQLException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/* String sql = """
|
||||
CREATE TABLE IF NOT EXISTS user (
|
||||
id integer PRIMARY KEY,
|
||||
name text);""";
|
||||
String sql2 = "SELECT * FROM user WHERE id > ?";
|
||||
String sql3 = "INSERT INTO user (id,name) VALUES (1,'test1')";
|
||||
try(Connection conn = connect();
|
||||
Statement stmt = conn.createStatement()){
|
||||
stmt.execute(sql);
|
||||
stmt.execute(sql3);
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql2);
|
||||
pstmt.setInt(1,0);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
while (rs.next()){
|
||||
System.out.println(rs.getInt("id"));
|
||||
}
|
||||
}catch (SQLException e){
|
||||
e.printStackTrace();
|
||||
return;
|
||||
} */
|
||||
}
|
Reference in New Issue
Block a user