P
P
postya2019-11-04 07:57:57
MySQL
postya, 2019-11-04 07:57:57

How to connect to a database from a file in a JavaFX application?

Wrote a desktop program in JavaFX.
There is a class for connecting to a database.
In the controller I call the method of this class.
Everything works fine, but I would like the url, user and password of the database to be taken not from the class, but from the
db.properties file, which is located in the root of the program, so that the user himself registers his settings for connecting to the database
How can this be done?
What I have:
Bathhouse class:

public class Database {

   private final static String DB_URL = "jdbc:mysql://localhost:3306/face?serverTimezone=UTC";
  private final static String DB_USER= "root";
  private final static String DB_PASSWORD = "root";

  public static Connection getConnection() throws SQLException {
    Connection connection = DriverManager.getConnection(DB_URL, DB_USER,  DB_PASSWORD);
    return connection;
  }

The getConnection method is called in the controller.
Connection con = Database.getConnection();
I tried to do this in the Database class:
try (InputStream input = Main.class.getClassLoader().getResourceAsStream("db.properties")) {

    Properties prop = new Properties();

    if (input == null) {
      System.out.println("Sorry, unable to find db.properties");
      return;
    }

    //load a properties file from class path, inside static method
    prop.load(input);
    
    //get the property value and print it out
    System.out.println(prop.getProperty("url"));
    System.out.println(prop.getProperty("user"));
    System.out.println(prop.getProperty("password"));

  } catch (IOException ex) {
    ex.printStackTrace();
  }

But try catch doesn't work

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question