Advertisement
Guest User

Untitled

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