2

My code to connect to database is using BasicDataSource as following, referring to Ans I suppose my code creates a physical connection to database ONCE and then provide pool connections afterward. My question is that, does my code provide pool connection?, if it does, should I keep the connection section of the code in the following method or in the constructor to provide efficient pooling ? and how should be the annotations for the state of the class ? @Stateful?

        // Connection section start
        BasicDataSource bs = new BasicDataSource();
        PreparedStatement ps = null;
        Connection con = null;
        try {
            bs.setDriverClassName("com.mysql.jdbc.Driver");
            bs.setUrl("jdbc:mysql://localhost/myDb");
            bs.setUsername("root");
            bs.setPassword("");
            con = bs.getConnection();
            System.out.println("Connecting");
        // Connection section end

            ps = con.prepareStatement("Select *"
                    + " from Client WHERE Username = ? ");
            ps.setString(1, username);
            ResultSet r = ps.executeQuery();
            if (r.next()) {
                con.close();
                return "true";
            }
2
  • 2
    Use the Apache Commonds DBCP connection pool. Don't write this stuff yourself. Commented Feb 12, 2013 at 1:12
  • @EJP, which stuff? would you give me an example? Commented Feb 12, 2013 at 1:29

1 Answer 1

4

BasicDataSource implements connection pooling. However, if you create a new pool each time then it's useless. Create the data source once and reuse it everywhere.

Usually, in Java EE you inject the data source. That is, the container manages the data source for you. Injecting a datasource in a bean is as simple as

@Resource
private DataSource movieDatabase;

See this example. Configuring the datasource depends on the container you are using, though. The same data source can be used for stateful and statless beans.

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

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.