Advertisement
Guest User

Untitled

a guest
Feb 17th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. package helpers;
  2.  
  3. import exception.JDBCConnectionException;
  4.  
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.util.ResourceBundle;
  9.  
  10. public class JdbcConnector {
  11.  
  12. Connection connection;
  13. String url;
  14. String driver;
  15. String user;
  16. String password;
  17.  
  18. public JdbcConnector() {
  19. ResourceBundle resourceBundle = ResourceBundle.getBundle("database");
  20.  
  21. url = resourceBundle.getString("url");
  22. driver = resourceBundle.getString("driver");
  23. user = resourceBundle.getString("user");
  24. password = resourceBundle.getString("password");
  25. }
  26.  
  27. public void startConnection() throws JDBCConnectionException {
  28. try {
  29. Class.forName(driver).newInstance();
  30. connection = DriverManager.getConnection(url, user, password);
  31. } catch (InstantiationException e) {
  32. e.printStackTrace();
  33. } catch (IllegalAccessException e) {
  34. e.printStackTrace();
  35. } catch (ClassNotFoundException e) {
  36. throw new JDBCConnectionException("Can't load database driver!", e);
  37. } catch (SQLException e) {
  38. throw new JDBCConnectionException("Can't connect to database!", e);
  39. }
  40.  
  41. if (connection == null)
  42. throw new JDBCConnectionException("Driver type is not correct in URL " +
  43. url + "!");
  44. }
  45.  
  46. public Connection getConnection() {
  47. return connection;
  48. }
  49.  
  50. public void closeConnection() throws JDBCConnectionException {
  51. if (connection != null) {
  52. try {
  53. connection.close();
  54. } catch (SQLException e) {
  55. throw new JDBCConnectionException("Can't close connection!", e);
  56. }
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement