Family-Map-Project / FamilyMapServer / FamilyMapServerStudent-master / src / dao / Database.java
Database.java
Raw
package dao;

import java.sql.*;

public class Database {
    private Connection conn;

    public Connection openConnection() throws DataAccessException
    {
        try
        {
            final String CONNECTION_URL = "jdbc:sqlite:FamilyMap.db";

            conn = DriverManager.getConnection(CONNECTION_URL);

            conn.setAutoCommit(false);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new DataAccessException("Unable to open connection to database");
        }

        return conn;
    }

    public Connection getConnection() throws DataAccessException
    {
        if(conn == null)
        {
            return openConnection();
        }
        else
        {
            return conn;
        }
    }

    public void closeConnection(boolean commit) throws DataAccessException
    {
        try
        {
            if (commit)
            {
                conn.commit();
            }
            else
            {
                conn.rollback();
            }

            conn.close();
            conn = null;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new DataAccessException("Unable to close database connection");
        }
    }

    public void clearTables() throws DataAccessException
    {
        String dropUsers = "DELETE FROM Users";
        String dropPersons = "DELETE FROM Persons";
        String dropEvents = "DELETE FROM Events";
        String dropAuthTokens = "DELETE FROM AuthTokens";

        try (PreparedStatement stmt = conn.prepareStatement(dropUsers))
        {
            stmt.executeUpdate();
        }
        catch (SQLException e)
        {
            throw new DataAccessException("SQL Error encountered while clearing User table");
        }

        try (PreparedStatement stmt = conn.prepareStatement(dropPersons))
        {
            stmt.executeUpdate();
        }
        catch (SQLException e)
        {
            throw new DataAccessException("SQL Error encountered while clearing Person table");
        }

        try (PreparedStatement stmt = conn.prepareStatement(dropEvents))
        {
            stmt.executeUpdate();
        }
        catch (SQLException e)
        {
            throw new DataAccessException("SQL Error encountered while clearing Event table");
        }

        try (PreparedStatement stmt = conn.prepareStatement(dropAuthTokens))
        {
            stmt.executeUpdate();
        }
        catch (SQLException e)
        {
            throw new DataAccessException("SQL Error encountered while clearing AuthToken table");
        }
    }
}