Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package app;
- import java.io.IOException;
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
- public class Database {
- private String hostname;
- private String database;
- private String username;
- private String password;
- private Connection conn;
- public Connection getConnection() {
- if(conn == null) {
- try {
- System.out.println("Getting properties file...");
- Properties prop = new Properties();
- InputStream input = Database.class.getResourceAsStream("database.properties");
- prop.load(input);
- this.hostname = prop.getProperty("hostname");
- this.database = prop.getProperty("database");
- this.username = prop.getProperty("username");
- this.password = prop.getProperty("password");
- input.close();
- } catch (IOException ex) {
- // Error Reading Properties File
- ex.printStackTrace();
- } finally {
- if (this.database != null) {
- try {
- System.out.println("Connecting to database...");
- Class.forName("com.mysql.jdbc.Driver");
- conn = DriverManager.getConnection("jdbc:mysql://" + this.hostname + "/" + this.database + "?user=" + this.username + "&password=" + this.password);
- } catch (SQLException ex) {
- // Error Connecting to Database
- ex.printStackTrace();
- } catch (ClassNotFoundException ex) {
- // Error Connecting to Database
- ex.printStackTrace();
- }
- }
- }
- }
- return conn;
- }
- }
Add Comment
Please, Sign In to add comment