import java.sql.*;

public class BasicJDBCDemo
{
    Connection conn;

    public static void main(String[] args)
    {
	System.out.println("Starting up...");
	new BasicJDBCDemo();
    }
 
    public BasicJDBCDemo()
    {
    try
	{
	    System.out.println("Class instanciated");
	    Class.forName("com.mysql.jdbc.Driver").newInstance();
	    String url = "jdbc:mysql://localhost/skontest";
	    conn = DriverManager.getConnection(url, "skon", "lukecool");
	    System.out.println("Connection: " + conn);
	    doTests();
	    conn.close();
	}
    catch (ClassNotFoundException ex) {System.out.println("a!");System.err.println(ex.getMessage());}
    catch (IllegalAccessException ex) {System.out.println("b!");System.err.println(ex.getMessage());}
    catch (InstantiationException ex) {System.out.println("c!");System.err.println(ex.getMessage());}
    catch (SQLException ex)           {System.out.println("d!");System.err.println(ex.getMessage());}
    }

    private void doTests()
    {
	doSelectTest();

	doInsertTest();  doSelectTest();
	doUpdateTest();  doSelectTest();
	doDeleteTest();  doSelectTest();
    }

    private void doSelectTest()
    {
	System.out.println("[OUTPUT FROM SELECT]");
	String query = "SELECT uuid, x, y, z from example";
    try
	{
	    Statement st = conn.createStatement();
	    ResultSet rs = st.executeQuery(query);
	    while (rs.next())
		{
		    String s = rs.getString("uuid");
		    int x = rs.getInt("x");
		    System.out.println(s + "   " + x);
		}
	}
    catch (SQLException ex)
	{
	    System.err.println(ex.getMessage());
	}
    }

    private void doInsertTest()
    {
	System.out.print("\n[Performing INSERT] ... ");
    try
	{
	    Statement st = conn.createStatement();
	    st.executeUpdate("INSERT INTO example " +
			     "VALUES (3, 'Pinhead ahoy', 200, 7, 5)");
	}
    catch (SQLException ex)
	{
	    System.err.println(ex.getMessage());
	}
    }

    private void doUpdateTest()
    {
	System.out.print("\n[Performing UPDATE] ... ");
    try
	{
	    Statement st = conn.createStatement();
	    st.executeUpdate("UPDATE example SET Z=4 WHERE uuid='Pinhead ahoy'");
	}
    catch (SQLException ex)
	{
	    System.err.println(ex.getMessage());
	}
    }

    private void doDeleteTest()
    {
	System.out.print("\n[Performing DELETE] ... ");
    try
	{
	    Statement st = conn.createStatement();
	    st.executeUpdate("DELETE FROM example WHERE uuid='Pinhead ahoy'");
	}
    catch (SQLException ex)
	{
	    System.err.println(ex.getMessage());
	}
    }
}
Topic revision: r1 - 2011-06-22 - JimSkon
 
This site is powered by the TWiki collaboration platformCopyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback