JDBC Basics
    (In 20 Minutes Flat)
          Craig S. Dickson




!
Agenda
    • What is JDBC?

    • Connecting to a database
    • Creating & Updating data

    • Querying data
    • Deleting data

!
About Me

    •   Software Architect, currently consulting
        with Adobe and BET

    •   15 years software development
        experience

    •   Sun Certified JavaEE Architect


!
Assumptions


    • Basic understanding of JavaSE 6
    • Basic understanding of relational
      database concepts and SQL



!
What is JDBC?

    •   JDBC = Java Database Connectivity

    • Provides basic API for connecting to
        relational databases

    • Part of JavaSE since version 1.1 (c. 1997)
    •   java.sql and javax.sql


!
JDBC Architecture




!
Driver

    String driver = “org.apache.derby.jdbc.EmbeddedDriver”;

    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }


    * this is even easier in JavaSE 6




!
Connect
    String connection_url = “jdbc:derby:uci_ext_db;create=true”;

    Connection connection = null;
    try {
        connection = DriverManager.getConnection(connection_url);
        // use the connection
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ignore) {
            }
        }
    }




!
Create A Table
      String sql = "create table candidates
                    (id int, name varchar(50), hired smallint)";

    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.execute(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ignore) {
            }
        }
    }



!
Create Rows
       String sql1 = "insert into candidates values
                                            (777, 'Craig Dickson', 0)";
    String sql2 = "insert into candidates values
                                            (888, 'Bill Gates', 0)";

    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.execute(sql1);
        statement.execute(sql2);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ignore) {
            }
        }
    }


!
Updating
    String sql = "update candidates set hired=1
                      where name='Craig Dickson'";

    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.executeUpdate(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ignore) {
            }
        }
    }



!
Selecting
    String sql = "select * from candidates";

    ResultSet resultSet = null;
    try {
        resultSet = statement.executeQuery(sql);
        printResults(resultSet);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException ignore) {
            }
        }
    }



!
Selecting (2)
    private void printResults(ResultSet resultSet)
                                              throws SQLException {

        System.err.println("ID    NAME             HIRED? ");
        System.err.println("---- -------------- -------");
        while (resultSet.next()) {
            String id = String.format("%-6s", resultSet.getInt(1));
            String name = String.format("%-16s", resultSet.getString(2));
            String hired = String.format("%-7s", resultSet.getBoolean(3));
            System.err.println(id + name + hired);
        }
    }




!
Selecting (3)

    ID     NAME             HIRED?
    ----   --------------   -------
    777    Craig Dickson    true
    888    Bill Gates       false




!
Deleting
    String sql = "delete from candidates where id=888";

    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.executeUpdate(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ignore) {
            }
        }
    }




!
In conclusion ...
    •   JDBC can be used to connect to relational
        databases from Java programs

    •   Allows all basic CRUD operations and can
        handle sophisticated multi-tier, multi-vendor
        environments

    •   Copious amounts of error handling required

    •   Can unintentionally create a dependency to a
        specific database vendor

!
Resources

    • Oracle’s JDBC Guide
        •   http://download.oracle.com/javase/6/docs/technotes/guides/jdbc/
            getstart/GettingStartedTOC.fm.html


    •   java.sql Package Javadocs
        •   http://download.oracle.com/javase/6/docs/api/java/sql/package-
            summary.html




!
Questions?


!

JDBC Basics (In 20 Minutes Flat)

  • 1.
    JDBC Basics (In 20 Minutes Flat) Craig S. Dickson !
  • 2.
    Agenda • What is JDBC? • Connecting to a database • Creating & Updating data • Querying data • Deleting data !
  • 3.
    About Me • Software Architect, currently consulting with Adobe and BET • 15 years software development experience • Sun Certified JavaEE Architect !
  • 4.
    Assumptions • Basic understanding of JavaSE 6 • Basic understanding of relational database concepts and SQL !
  • 5.
    What is JDBC? • JDBC = Java Database Connectivity • Provides basic API for connecting to relational databases • Part of JavaSE since version 1.1 (c. 1997) • java.sql and javax.sql !
  • 6.
  • 7.
    Driver String driver = “org.apache.derby.jdbc.EmbeddedDriver”; try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } * this is even easier in JavaSE 6 !
  • 8.
    Connect String connection_url = “jdbc:derby:uci_ext_db;create=true”; Connection connection = null; try { connection = DriverManager.getConnection(connection_url); // use the connection } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException ignore) { } } } !
  • 9.
    Create A Table String sql = "create table candidates (id int, name varchar(50), hired smallint)"; Statement statement = null; try { statement = connection.createStatement(); statement.execute(sql); } catch (SQLException e) { e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException ignore) { } } } !
  • 10.
    Create Rows String sql1 = "insert into candidates values (777, 'Craig Dickson', 0)"; String sql2 = "insert into candidates values (888, 'Bill Gates', 0)"; Statement statement = null; try { statement = connection.createStatement(); statement.execute(sql1); statement.execute(sql2); } catch (SQLException e) { e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException ignore) { } } } !
  • 11.
    Updating String sql = "update candidates set hired=1 where name='Craig Dickson'"; Statement statement = null; try { statement = connection.createStatement(); statement.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException ignore) { } } } !
  • 12.
    Selecting String sql = "select * from candidates"; ResultSet resultSet = null; try { resultSet = statement.executeQuery(sql); printResults(resultSet); } catch (SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException ignore) { } } } !
  • 13.
    Selecting (2) private void printResults(ResultSet resultSet) throws SQLException { System.err.println("ID NAME HIRED? "); System.err.println("---- -------------- -------"); while (resultSet.next()) { String id = String.format("%-6s", resultSet.getInt(1)); String name = String.format("%-16s", resultSet.getString(2)); String hired = String.format("%-7s", resultSet.getBoolean(3)); System.err.println(id + name + hired); } } !
  • 14.
    Selecting (3) ID NAME HIRED? ---- -------------- ------- 777 Craig Dickson true 888 Bill Gates false !
  • 15.
    Deleting String sql = "delete from candidates where id=888"; Statement statement = null; try { statement = connection.createStatement(); statement.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException ignore) { } } } !
  • 16.
    In conclusion ... • JDBC can be used to connect to relational databases from Java programs • Allows all basic CRUD operations and can handle sophisticated multi-tier, multi-vendor environments • Copious amounts of error handling required • Can unintentionally create a dependency to a specific database vendor !
  • 17.
    Resources • Oracle’s JDBC Guide • http://download.oracle.com/javase/6/docs/technotes/guides/jdbc/ getstart/GettingStartedTOC.fm.html • java.sql Package Javadocs • http://download.oracle.com/javase/6/docs/api/java/sql/package- summary.html !
  • 18.

Editor's Notes

  • #2 - Good afternoon\n\n- We’re going to take a quick look at the basic elements that make up JDBC\n
  • #3 - Talk about exactly where JDBC fits into the Java language\n\n- Then look at some examples of the 4 basic CRUD operations for databases - Create, Read, Update and Delete\n\n
  • #4 - Enterprise developer and architect\n\n- I work with these kinds of technologies on an almost daily basis\n\n\n- How about you? Anyone with JDBC experience? How about experience connecting to databases from other languages like .NET or PHP?\n\n\n
  • #5 - This is a quick and shallow overview of JDBC so the pre-requisites are pretty light\n\n- Hopefully you know how to write and compile simple Java programs\n\n- Also, some knowledge of basic relationaly database concepts like tables and the SQL language\n
  • #6 - In a nutshell, JDBC is simply an API that allows you to make a connection from a Java application to a relational database and execute SQL statements against that database\n\n- It is part of the core Java APIs and has been around since very early on in Java’s life\n\n- All of the API is contained in 2 packages, java.sql contains the basic API, the javax.sql contains some more advanced API elements\n
  • #7 - JDBC is the piece that sits between your code and the database\n\n- There is the standard API code, combined with a vendor specific Driver that knows how to talk to a particular database\n\n- In theory you can swap in a different driver and your program can work with a different database\n
  • #8 - To initialize a Driver you simply use the standard Java classloader to load the Driver class\n\n- In this example we are loading a driver to talk to an Apache Derby database\n\n- In JavaSE 6, you don’t even need to do this, it happens in the background as part of the new Service API\n\n
  • #9 - url is a database specific string containing information on how to connect to the database, including credentials and other details\n\n- use the DriverManager to actually create the connection\n\n- notice the error handling\n
  • #10 - pretty basic sql table create statement\n\n- notice that Derby doesn’t support a boolean column type, so we use an integer, 0 for false, 1 for true\n\n- we have now introduced a little vendor dependency\n\n- use the connection to get a Statement object, and then execute the SQL\n
  • #11 - once again, pretty standard SQL for inserting a row into a database\n\n- id column, name column, integer boolean column\n\n- once again we simply get a Statement object from our connection, then use it to run SQL against the database\n
  • #12 - basic sql update statement\n\n- changing the value of the hired column to the value 1, and we use the where clause to specify which row we want to update\n\n- use the executeUpdate method call instead\n
  • #13 - standard sql select statement, we want all columns from all rows\n\n- use the executeQuery method, which returns a ResultSet object\n\n- in this example we pass the result set to another method to print out the results\n
  • #14 - so here is the printResults method, notice the ResultSet being passed into this method as a parameter\n\n- notice the while loop, this allows us to process each row in the result set in turn\n\n- notice the resultSet.get methods, which include a 1-based column index\n\n- if we run this code, can anyone tell me what actually gets printed to the screen?\n
  • #15 - notice the true value for the first row, even though the value in the database was the number 1, the JDBC API was able to convert that to a boolean for us\n
  • #16 - Of course once you have been inserting and updating data for a while, you inevitably need to delete some data\n\n- Notice the standard SQL delete statement, where we are saying to delete all rows in the candidates table whose id column has the value 888 in it\n\n- Get the Statement object from the connection and use it to run the SQL\n
  • #17 \n
  • #18 \n
  • #19 \n