/*
 * [ConnectJDBCPostgreSQL.java]
 *
 * Summary: Demonstrate the how to connect to a PostgreSQL Server Database with JBDC.
 *
 * Copyright: (c) 2011-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 2011-02-15 initial version
 */
package com.mindprod.example;

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

import static java.lang.System.*;

/**
 * Demonstrate the how to connect to a PostgreSQL Server Database with JBDC.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2011-02-15 initial version
 * @since 2011-02-15
 */
public class ConnectJDBCPostgreSQL
    {
    /**
     * which database
     */
    private static final String DATA_BASE_NAME = "squirrels";

    /**
     * class name of the JDBC driver
     * You must install the postgresql-9.0-801.jdbc4.jar containing the driver in the ext dir.
     * Download it separately from http://jdbc.postgresql.org
     */
    private static final String DRIVER_CLASS_NAME = "org.postgresql.Driver";

    /**
     * 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
     *
     * @return Connection to the database
     * @throws java.sql.SQLException
     */
    private static Connection connect() throws SQLException
        {
        try
            {
            Class.forName( DRIVER_CLASS_NAME );  // just load class. Don't retain handle to driver.
            }
        catch ( Exception e )
            {
            err.println( "can't load SQL Server driver: " + e.getMessage() );
            }
        return DriverManager.getConnection( "jdbc:postgresql:" + DATA_BASE_NAME,
                USERNAME,
                PASSWORD );
        }

    /**
     * initialise the database
     *
     * @param args not used
     *
     * @throws java.sql.SQLException
     */
    public static void main( String[] args ) throws SQLException
        {
        conn = connect();
        final DatabaseMetaData dbmd = conn.getMetaData(); //get MetaData to confirm connection
        out.println( "Connection to " + dbmd.getDatabaseProductName() + " " +
                     dbmd.getDatabaseProductVersion() + " successful.\n" );
        // ...
        conn.close();
        }
    }