Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. package databaseConnection;
  2.  
  3. import java.sql.*;
  4.  
  5. /**
  6.  * Created by pawel on 25.03.2017.
  7.  */
  8. abstract class DatabaseQuery {
  9.  
  10.     public static final String JDBC_URL = "jdbc:hsqldb:file:data/rozkazer.db";
  11.     public static final String USER = "SA";
  12.     public static final String PASSWORD = "";
  13.     public static final String DRIVER_CLASSNAME = "org.hsqldb.jdbcDriver";
  14.     private String sql;
  15.     private Connection connection;
  16.     private Statement statement;
  17.     protected ResultSet resultSet;
  18.  
  19.     public DatabaseQuery(String sql){
  20.         this.sql = sql;
  21.     }
  22.  
  23.     public void execute(){
  24.         try {
  25.             connectToDatabase();
  26.             executeSql();
  27.             process();
  28.             close();
  29.         } catch (ClassNotFoundException e) {
  30.             e.printStackTrace();
  31.         } catch (SQLException e) {
  32.             e.printStackTrace();
  33.         }
  34.  
  35.     }
  36.  
  37.     private void close() throws SQLException {
  38.         resultSet.close();
  39.         statement.execute("SHUTDOWN");
  40.         statement.close();
  41.         connection.close();
  42.     }
  43.  
  44.     abstract protected void process() throws SQLException;
  45.  
  46.     private void executeSql() throws SQLException {
  47.         statement = connection.createStatement();
  48.         resultSet = statement.executeQuery(sql);
  49.     }
  50.  
  51.     private void connectToDatabase() throws ClassNotFoundException, SQLException {
  52.  
  53.         Class.forName(DRIVER_CLASSNAME);
  54.         connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement