N
N
NoMoneyException2017-01-21 16:11:43
MySQL
NoMoneyException, 2017-01-21 16:11:43

Where and how to correctly open a connection using JDBC + DAO?

Hello. I am looking for and for some reason I cannot find some reference implementation of the DAO pattern on pure JDBC.
How I do it:
Create a DBPool class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBPool {
    private static DBPool instance;

    private static final String USER = "root";
    private static final String PASSWORD = "root";
    private static final String URL = "jdbc:mysql://localhost:3306/shop?useSSL=false";

    private DBPool() {

    }

    public static DBPool getInstance() {
        if (instance == null)
            instance = new DBPool();
        return instance;
    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    public void putConnection(Connection connection) throws SQLException {
        if (connection != null)
            connection.close();
    }
}

And then I use it in ready-made DAO implementations. That is, I open a connection there and close it. However, somewhere I met that such a connection is opened in DAOFactroy, and not in a separate class, like mine. So how is it done right? I would be grateful for an answer or a link.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rou1997, 2017-01-21
@Rou1997

And what is the essence of such a question?
Assume that there really is a single correct solution for such a general question. :)
But anyway, why do it now, when you can not stop there and continue further implementation of the DAO, other work, and then, if problems arise, then just redo it, because in this case it’s not difficult at all?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question