0

Lets say I have desktop application with simple login - here, in this part i have to create Connection, prepared statement which compares username and password. I use cardlayout- and for example, on another card (JPanel) i have JTable and JButton which retrieves values from SQL table to my JTable.... on third JPanel i have for example fields for name and password - using for new employee - he will give his name and password - after button click data will be inserted to DB

Now my Question: How does it work in real application? Shall I make one static method (e.g. getDBConnection()) which will create connection (first for login - after login close connection, then create another connection when i want to select from DB then close it and again if i want to insert something?) `

or how to do it in smarter/ proper way?

1

2 Answers 2

1

You can write a properties file specific to your application and write a class to load it.

MyDatabaseProperties.properties

database.jdbc.url = jdbc:mysql://localhost:3306/database
database.jdbc.driver = "com.mysql.jdbc.Driver"
database.jdbc.username = "USERNAME"
database.jdbc.password = "PASSWORD"

Properties.java:

public class Properties {
    private static final String PROPERTIES_FILE = "MyDatabaseProperties.properties";
    private static final Properties PROPERTIES = new Properties();

    static {
        try {
            PROPERTIES.load(new FileInputStream("MyDatabaseProperties.properties"));
        } catch (IOException e) {
            // THROW YOUR EXCEPTION HERE.
        }
    }
}

You will find an excellent material on this subject here.

Sign up to request clarification or add additional context in comments.

Comments

0

You can create a DAO (Data Access Object) to access the table Employee, named DAOEmployee for instance (note that this class will contain methods such as addEmployee, removeEmployee, getEmployees). Then, you can have a class (DataBaseConfiguration), responsible of returning the connection to the database (using a static method, for instance).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.