package Database;

import java.sql.*;

/**
 * Describe class DbaseTest here.
 *
 *
 * Created: Mon Sep 26 17:23:13 2005
 *
 * @author <a href="mailto:jsantore@eagle">John Santore</a>
 * @version 1.0
 */


public class DbaseTest {

    /**
     * Creates a new <code>DbaseTest</code> instance.
     *
     */
    public DbaseTest() throws java.lang.ClassNotFoundException {
	//lets load the mysql driver
	Class.forName("com.mysql.jdbc.Driver");
    }

    public static void main(String[] args){

	//create an instanct of the test class and run it.
	//there is a chance of a ClassNotFoundException if the mysql 
	//driver is not in your classpath.
	DbaseTest connTest;
	try {
	 connTest= new DbaseTest();
	 connTest.testDB();
	}
	catch (java.lang.ClassNotFoundException e)
	    {
		System.out.println("DEBUG: couldn't find the mysql driver!!");
	    }

	
	
    }

    protected void testDB(){

	//need several strings for the connection
	String dbHost = "192.168.150.49";
	String dbName = "playing";
	String user = "johns";
	String password = "play";
	//create the connection
	Connection con = getConnection(dbHost, dbName, user, password);
	Statement stmt = null;
	ResultSet rs = null;
	
	try {
	    //try a sinple select query
	    stmt = con.createStatement();
	    rs = stmt.executeQuery("select * from customers_cust");
	    //have to move to first row of result set
	    rs.first(); 
	    //retrieve the cust_email field from the result
	    String sample = rs.getString("cust_email");
	    //print it out to show that the data was retrieved.
	    System.out.println(sample);
	    
	} 
	catch (Exception e)
	    {
		System.out.println("THERE WAS AN ERROR "+e.getMessage() );
	    }
	finally {
	    // it is a good idea to release
	    // resources in a finally{} block
	    // in reverse-order of their creation
	    // if they are no-longer needed
	    //above comments (and code below) are straight from the tutorial
	    //that I used to help me along.
	    if (rs != null) {
		try {
		    rs.close();
		} catch
		    (SQLException sqlEx) { // ignore }
		    
		    rs = null;
		}
		
	        if (stmt != null) {
		    try {
			stmt.close();
		    } catch (SQLException sqlEx) {
			// ignore }
			
			stmt = null;
		    }
		}
	    }
	}	
	

    }

    protected Connection getConnection(String host, String dataBase,
				       String user, String password){
	//construct the host string.
	String url="jdbc:mysql://" + host + "/"+dataBase+ "?user="+
	    user+"&password="+password;
	try{
	    //actually create the connection.
	    Connection con = DriverManager.getConnection(url);
	    return con;
	}
	catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
	return null;
    }

}
