package com.mindprod.example;

import static java.lang.System.err;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * TestDerbyEmbedded: demonstrate the how to connect to a Apache Derby Database via JDBC and the embedded driver.
 * <p/>
 * composed with IntelliJ IDEA
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0, 2007-09-26
 */
@SuppressWarnings( { "WeakerAccess", "UnusedDeclaration" } )
public class TestDerbyEmbedded
    {
// ------------------------------ FIELDS ------------------------------

    /**
     * which database
     */
    private static final String DATABASENAME = "SQUIRRELS";

    /**
     * class name of the JDBC driver
     */
    private static final String DRIVERCLASSNAME =
            "org.apache.derby.jdbc.EmbeddedDriver";

    /**
     * access PASSWORD
     */
    private static final String PASSWORD = "sesame";

    /**
     * basic URL to access the database
     */
    @SuppressWarnings( { "ConstantNamingConvention" } )
    private static final String URL = "jdbc:derby:";

    /**
     * login name of user
     */
    private static final String USERNAME = "charlie";

    /**
     * The connection.  Handle to the database
     */
    @SuppressWarnings( { "FieldCanBeLocal", "UnusedDeclaration" } )
    private Connection conn;

// -------------------------- STATIC METHODS --------------------------

    /**
     * glue parts of connection URL together.
     *
     * @return complete URL to access database.
     */
    private static String getConnectionUrl()
        {
        return URL + DATABASENAME + ";create=true;";
        }

// -------------------------- OTHER METHODS --------------------------

    /**
     * connect to the database
     */
    private void init()
        {
        try
            {
            Class.forName( DRIVERCLASSNAME );
            }
        catch ( Exception e )
            {
            err.println( "can't load Derby Embedded JDBC driver: "
                         + e.getMessage() );
            }
        try
            {
            conn =
                    DriverManager.getConnection( getConnectionUrl(),
                            USERNAME,
                            PASSWORD );
            }
        catch ( SQLException e )
            {
            err.println( "can't connect to Derby via the JDBC Embedded driver: "
                         + e.getMessage() );
            }
        }
    }