Advertisement
Guest User

Untitled

a guest
May 5th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.89 KB | None | 0 0
  1. package database;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. //import java.util.logging.Logger;
  10.  
  11. /**
  12.  * The connection to the database
  13.  *
  14.  * @author mobe
  15.  *
  16.  */
  17. public class DBConnectionManager {
  18.     //private static final Logger logger = UserSession.getInstance().getLog(DBConnectionManager.class.getName());
  19.  
  20.     private static int queries = 0;
  21.  
  22.     /** The only ShippingDB instance */
  23.     private static DBConnectionManager dbo;
  24.  
  25.     /** Our precious connection */
  26.     private static Connection conn;
  27.  
  28.     /**
  29.      * Creates a connection to the database. This constructor is private so that
  30.      * getInstance can control the instantiation of connections
  31.      *
  32.      * @param host
  33.      *            String med ip eller domenenavn der databasen kj�rer
  34.      * @param db
  35.      *            String med navnet p� databasen
  36.      * @param user
  37.      *            String med brukernavnet som skal brukes
  38.      * @param password
  39.      *            String med passordet til brukeren
  40.      *
  41.      */
  42.     private DBConnectionManager(String host, String db, String user, String password){
  43.         try {
  44.             long start = System.currentTimeMillis();
  45.             Class.forName("com.mysql.jdbc.Driver");
  46.             System.out.print("getting connection ... ");
  47.             conn = DriverManager.getConnection("jdbc:mysql://" + host + "/" + db + "?allowMultiQueries=true", user,
  48.                     password);
  49.             System.out.println("done");
  50.             System.out.println("Used " + ((System.currentTimeMillis() - start) / 1000.0)
  51.                     + " seconds to connect with database");
  52.         } catch (ClassNotFoundException e) {
  53.             e.printStackTrace();
  54.         } catch (SQLException e) {
  55.             e.printStackTrace();
  56.         }
  57.     }
  58.  
  59.     public static void closeAll() {
  60.         if (conn == null)
  61.             return;
  62.         try {
  63.             conn.close();
  64.         } catch (SQLException e) {
  65.             try {
  66.                 conn.close();
  67.             } catch (SQLException e1) {
  68.                 e1.printStackTrace();
  69.             }
  70.             e.printStackTrace();
  71.         }
  72.     }
  73.  
  74.     public boolean isConnected() {
  75.         try {
  76.             return conn != null && (!conn.isClosed());
  77.         } catch (SQLException e) {
  78.             e.printStackTrace();
  79.             return false;
  80.         }
  81.     }
  82.  
  83.     private static void queries() {
  84.         queries++;
  85.     }
  86.  
  87.     /**
  88.      * Returns an instance of this class, which represents a connection to the
  89.      * database
  90.      *
  91.      * @return an instance of this class
  92.      * @throws DataAccessException
  93.      */
  94.     public static DBConnectionManager getInstance() {
  95.         if (dbo == null) {
  96.             //SettingsDaoFactory.getInstance().getSettings();
  97.             //ISettings s = SettingsDaoFactory.getInstance().getSettings();
  98.             String host = "localhost";
  99.             String db = "jon";
  100.             String user = "root";
  101.             String password = "heidu1";
  102.             dbo = new DBConnectionManager(host, db, user, password);
  103.         }
  104.         return dbo;
  105.     }
  106.  
  107.     public boolean isAutoCommit() {
  108.         try {
  109.             return conn.getAutoCommit();
  110.         } catch (SQLException e) {
  111.             e.printStackTrace();
  112.             return false;
  113.         }
  114.     }
  115.  
  116.     /**
  117.      * Closes connection with database forever
  118.      */
  119.     public static void close() {
  120.         if (conn == null)
  121.             return;
  122.         try {
  123.             conn.close();
  124.             dbo = null;
  125.         } catch (SQLException sqle) {
  126.             sqle.printStackTrace();
  127.         } finally {
  128.             System.out.println(queries + " queries");
  129.             queries = 0;
  130.             try {
  131.                 if (conn != null) {
  132.                     conn.close();
  133.                     dbo = null;
  134.                 }
  135.             } catch (SQLException sqle) {
  136.                 System.err.println("Could not disconnect from database.");
  137.                 System.out.println("Could not disconnect from database.");
  138.                 sqle.printStackTrace();
  139.             }
  140.         }
  141.     }
  142.  
  143.     /**
  144.      * Closes statement
  145.      *
  146.      * @param s
  147.      *            statement to be closed
  148.      */
  149.     public static void close(Statement s) {
  150.         close(s, null, null);
  151.     }
  152.  
  153.     /**
  154.      * Closes prepared statement
  155.      *
  156.      * @param ps
  157.      *            prepared statement to be closed
  158.      */
  159.     public static void close(PreparedStatement ps) {
  160.         close(null, ps, null);
  161.     }
  162.  
  163.     /**
  164.      * Closes result set
  165.      *
  166.      * @param rs
  167.      *            result set to be closed
  168.      */
  169.     public static void close(ResultSet rs) {
  170.         close(null, null, rs);
  171.     }
  172.  
  173.     /**
  174.      * Closes a statement and a prepared statement
  175.      *
  176.      * @param s
  177.      *            statement to be closed
  178.      * @param ps
  179.      *            prepared statement to be closed
  180.      */
  181.     public static void close(Statement s, PreparedStatement ps) {
  182.         close(s, ps, null);
  183.     }
  184.  
  185.     /**
  186.      * Closes a statement and a result set
  187.      *
  188.      * @param s
  189.      *            statement to be closed
  190.      * @param rs
  191.      *            result set to be closed
  192.      */
  193.     public static void close(Statement s, ResultSet rs) {
  194.         close(s, null, rs);
  195.     }
  196.  
  197.     /**
  198.      * Closes a prepared statement and a result set
  199.      *
  200.      * @param ps
  201.      *            prepared statement to be closed
  202.      * @param rs
  203.      *            result set to be closed
  204.      */
  205.     public static void close(PreparedStatement ps, ResultSet rs) {
  206.         close(null, ps, rs);
  207.     }
  208.  
  209.     /**
  210.      * Closes a statement, a prepared statement and a result set
  211.      *
  212.      * @param s
  213.      *            statement to be closed
  214.      * @param ps
  215.      *            prepared statement to be closed
  216.      * @param rs
  217.      *            result set to be closed
  218.      */
  219.     public static void close(Statement s, PreparedStatement ps, ResultSet rs) {
  220.         if (s == null && ps == null && rs == null)
  221.             return;
  222.         try {
  223.             if (rs != null)
  224.                 rs.close();
  225.             if (s != null)
  226.                 s.close();
  227.             if (ps != null)
  228.                 ps.close();
  229.         } catch (SQLException sqle) {
  230.             sqle.printStackTrace();
  231.         } finally {
  232.             try {
  233.                 if (s != null)
  234.                     s.close();
  235.                 if (ps != null)
  236.                     ps.close();
  237.                 if (rs != null)
  238.                     rs.close();
  239.             } catch (SQLException sqle) {
  240.                 System.err.println("Could not close.");
  241.                 System.out.println("Could not close.");
  242.                 sqle.printStackTrace();
  243.             }
  244.         }
  245.     }
  246.  
  247.     /**
  248.      * Disables auto commit and enables Isolation-level
  249.      * TRANSACTION_SERIALIZABLE, which means that the rows accessed during
  250.      * transactions will be locked for this transactions life time
  251.      */
  252.     public void startTransaction() {
  253.         System.out.print("starting transaction ...");
  254.         try {
  255.             conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
  256.             conn.setAutoCommit(false);
  257.             System.out.println(" autocommit is " + conn.getAutoCommit());
  258.         } catch (SQLException e) {
  259.             e.printStackTrace();
  260.         }
  261.     }
  262.  
  263.     /**
  264.      * Closes transaction and enables auto commit
  265.      *
  266.      * @throws DataAccessException
  267.      */
  268.     public void closeTransaction() {
  269.         System.out.print("\nstopping transaction ... ");
  270.         try {
  271.             conn.setAutoCommit(true);
  272.             System.out.println(" autocommit is " + conn.getAutoCommit());
  273.         } catch (SQLException e) {
  274.             e.printStackTrace();
  275.         }
  276.     }
  277.  
  278.     /**
  279.      * Commits current transactions
  280.      */
  281.     public void commit() {
  282.         try {
  283.             if (!conn.getAutoCommit()) {
  284.                 System.out.print("\nautocommit is disabled, committing ... ");
  285.                 conn.commit();
  286.                 System.out.println(" done committing");
  287.             } else {
  288.                 System.err.println("autocommit enabled, does nothing!");
  289.             }
  290.         } catch (SQLException e) {
  291.             e.printStackTrace();
  292.         }
  293.     }
  294.  
  295.     /**
  296.      * Rolls back current transactions
  297.      */
  298.     public void rollback() {
  299.         try {
  300.             if (!(conn.getAutoCommit())) {
  301.                 conn.rollback();
  302.                 System.out.println("\n\t\t\tROLLED BACK!!!!!!1!\n\n");
  303.                 System.err.println("Rolled back changes");
  304.             }
  305.         } catch (SQLException e) {
  306.             e.printStackTrace();
  307.         }
  308.     }
  309.  
  310.     /**
  311.      * Creates a PreparedStatement from string
  312.      *
  313.      * @param query
  314.      *            The query to convert
  315.      * @return a prepared statement
  316.      */
  317. //  public PreparedStatement prepareStatement(String query) {
  318. //      return prepareStatement(query, PreparedStatement.NO_GENERATED_KEYS);
  319. //  }
  320.  
  321. //  /**
  322. //   * Creates a PreparedStatement from string
  323. //   *
  324. //   * @param query
  325. //   *            the query
  326. //   * @param arg1
  327. //   *            PreparedStatement.NO_GENERATED_KEYS or
  328. //   *            PreparedStatement.RETURN_GENERATED_KEYS
  329. //   * @return a prepared statement
  330. //   */
  331. //  public PreparedStatement prepareStatement(String query, int arg1){
  332. //      try {
  333. //          queries();
  334. //          // System.out.println(queries + "\tPrepared statement:\t" + query);
  335. //          return conn.prepareStatement(query, arg1);
  336. //      } catch (SQLException sqle) {
  337. //          sqle.printStackTrace();
  338. //      }
  339. //  }
  340.  
  341.     /**
  342.      * Queries the query, only for SELECTS as it is read only
  343.      *
  344.      * @param query
  345.      *            the select query (not an update, insert or delete, as it is
  346.      *            read only)
  347.      * @return the ResultSet created
  348.      * @throws DataAccessException
  349.      */
  350.     public ResultSet runQuery(String query) {
  351.         Statement stmt = null;
  352.         ResultSet rs = null;
  353.         try {
  354.             stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  355.             rs = stmt.executeQuery(query);
  356.             // System.out.println(queries + "\tResultSet:\t\t" + query);
  357.             queries();
  358.         } catch (SQLException e) {
  359.             e.printStackTrace();
  360.         }
  361.         return rs;
  362.     }
  363.  
  364.     public void executeUpdate(String query) throws SQLException {
  365.         // System.out.println("query: " + query);
  366.         conn.createStatement().executeUpdate(query);
  367.     }
  368. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement