if the application is small you can create a connection object each time you hit the database but if the number of request to the database is pretty high you can use Connection pool you can use BasicDataSource which is an apache project use singleton pattern to wrapp the instance of basic dataSource and retrieve the connection Object each time you want from that wrapping class
DataWrapper
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
public class DataWrapper {
private static DataSource datasource;
private static void initialize() throws Exception {
Properties props = new Properties();
props.put("url", "jdbc:mysql://localhost:3306/testbd");
props.put("password", "root");
props.put("username", "root");
props.put("driverClassName", "com.mysql.jdbc.Driver");
props.put("initialSize", "10");
props.put("maxTotal", "15");
props.put("maxIdle", "10");
props.put("minIdle", "5");
datasource = BasicDataSourceFactory.createDataSource(props);
}
public static synchronized Connection getConnection() throws Exception {
if (datasource == null) {
initialize();
}
return datasource.getConnection();
}
}
caller
Connection con=DataWrapper.getConnection();
PreparedStatement statement=con.prepareStatement("select * from users");
ResultSet result= statement.executeQuery();
result.next();
System.out.println(result.getString(1));
//dont forget to close the connection object
con.close();