/*
 * [ConnectJDBCMySQLPooling.java]
 *
 * Summary: Demonstrate the how to connect to a MySQL Server Database with JBDC and connection pooling.
 *
 * Copyright: (c) 2007-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2007-09-17
 */
package com.mindprod.example;
import org.apache.tomcat.dbcp.dbcp.DriverManagerConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolingDataSource;
import org.apache.tomcat.dbcp.pool.impl.GenericObjectPool;
import java.sql.Connection;
import java.sql.SQLException;
/**
 * Demonstrate the how to connect to a MySQL Server Database with JBDC and connection pooling.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2007-09-17
 * @since 2007-09-17
 */
public class ConnectJDBCMySQLPooling
    {
    /**
     * which database
     */
    private static final String DATABASENAME = "squirrels";
    /**
     * access PASSWORD
     */
    private static final String PASSWORD = "sesame";
    /**
     * login name of user
     */
    private static final String USERNAME = "charlie";
    /**
     * The connection.  Handle to the database
     */
    private static Connection conn;
    /**
     * connect to the database
     */
    private static Connection connect() throws SQLException
        {
        // get JDBC connection to MySQL database from a connection pool.
        // Jar containing the Connector/J JDBC driver: mysql-connector-java-5.1.15-bin.jar must be downloaded and
        // placed on the classpath.
        // You must also have tomcat-dbcp.jar on the classpath.
        // You must configure to allow external TCP/IP connections or else localhost won't work either.
        final GenericObjectPool cp = new GenericObjectPool( null );
        final DriverManagerConnectionFactory dmcf = new DriverManagerConnectionFactory( "jdbc:mysql://localhost/" +
                                                                                        DATABASENAME,
                USERNAME,
                PASSWORD
        );
        final PoolableConnectionFactory pcf = new PoolableConnectionFactory( dmcf, cp, null, null, false, true );
        // pcf is not used???
        final PoolingDataSource ds = new PoolingDataSource( cp );
        return ds.getConnection();
        }
    /**
     * initialise the database
     *
     * @param args not used
     */
    public static void main( String[] args ) throws SQLException
        {
        conn = connect();
        // ...
        conn.close();
        }
    }