Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package jdbc;
  7.  
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.sql.Connection;
  11. import java.sql.DriverManager;
  12. import java.sql.SQLException;
  13. import java.util.Properties;
  14.  
  15. /**
  16. *
  17. * @author dskaster
  18. */
  19. public class ConnectionFactory {
  20.  
  21. private static ConnectionFactory instance = null;
  22.  
  23. private String dbHost;
  24. private String dbPort;
  25. private String dbName;
  26. private String dbUser;
  27. private String dbPassword;
  28.  
  29. private ConnectionFactory() {
  30. }
  31.  
  32. public static ConnectionFactory getInstance() {
  33. if (instance == null) {
  34. instance = new ConnectionFactory();
  35. }
  36.  
  37. return instance;
  38. }
  39.  
  40. public void readProperties() throws IOException {
  41. Properties properties = new Properties();
  42.  
  43. try {
  44. String path = "jdbc/datasource.properties";
  45. InputStream input = this.getClass().getClassLoader().getResourceAsStream(path);
  46. properties.load(input);
  47.  
  48. dbHost = properties.getProperty("host");
  49. dbPort = properties.getProperty("port");
  50. dbName = properties.getProperty("name");
  51. dbUser = properties.getProperty("user");
  52. dbPassword = properties.getProperty("password");
  53. } catch (IOException ex) {
  54. System.err.println(ex.getMessage());
  55.  
  56. throw new IOException("Erro ao obter informações do banco de dados.");
  57. }
  58. }
  59.  
  60. public Connection getConnection() throws ClassNotFoundException, IOException, SQLException {
  61. Connection connection = null;
  62.  
  63. try {
  64. Class.forName("org.postgresql.Driver");
  65.  
  66. readProperties();
  67.  
  68. String url = "jdbc:postgresql://" + dbHost + ":" + dbPort + "/" + dbName;
  69.  
  70. connection = DriverManager.getConnection(url, dbUser, dbPassword);
  71. } catch (ClassNotFoundException ex) {
  72. System.err.println(ex.getMessage());
  73.  
  74. throw new ClassNotFoundException("Erro de conexão ao banco de dados.");
  75. } catch (SQLException ex) {
  76. System.err.println(ex.getMessage());
  77.  
  78. throw new SQLException("Erro de conexão ao banco de dados.");
  79. }
  80.  
  81. return connection;
  82. }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement