Guest User

Untitled

a guest
Feb 13th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. package app;
  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 Database {
  11.  
  12. private String hostname;
  13. private String database;
  14. private String username;
  15. private String password;
  16. private Connection conn;
  17.  
  18. public Connection getConnection() {
  19.  
  20. if(conn == null) {
  21.  
  22. try {
  23.  
  24. System.out.println("Getting properties file...");
  25. Properties prop = new Properties();
  26. InputStream input = Database.class.getResourceAsStream("database.properties");
  27. prop.load(input);
  28. this.hostname = prop.getProperty("hostname");
  29. this.database = prop.getProperty("database");
  30. this.username = prop.getProperty("username");
  31. this.password = prop.getProperty("password");
  32. input.close();
  33.  
  34. } catch (IOException ex) {
  35.  
  36. // Error Reading Properties File
  37. ex.printStackTrace();
  38.  
  39. } finally {
  40.  
  41. if (this.database != null) {
  42.  
  43. try {
  44. System.out.println("Connecting to database...");
  45. Class.forName("com.mysql.jdbc.Driver");
  46. conn = DriverManager.getConnection("jdbc:mysql://" + this.hostname + "/" + this.database + "?user=" + this.username + "&password=" + this.password);
  47.  
  48. } catch (SQLException ex) {
  49.  
  50. // Error Connecting to Database
  51. ex.printStackTrace();
  52.  
  53. } catch (ClassNotFoundException ex) {
  54.  
  55. // Error Connecting to Database
  56. ex.printStackTrace();
  57.  
  58. }
  59.  
  60. }
  61.  
  62. }
  63.  
  64. }
  65.  
  66. return conn;
  67.  
  68. }
  69.  
  70. }
Add Comment
Please, Sign In to add comment