SlideShare a Scribd company logo
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?


!

More Related Content

PPT
JDBC – Java Database Connectivity
PPTX
1. java database connectivity (jdbc)
PPTX
JDBC ppt
PPT
Java database connectivity with MYSQL
PPS
Jdbc example program with access and MySql
PPT
JDBC Java Database Connectivity
PPT
JDBC Tutorial
JDBC – Java Database Connectivity
1. java database connectivity (jdbc)
JDBC ppt
Java database connectivity with MYSQL
Jdbc example program with access and MySql
JDBC Java Database Connectivity
JDBC Tutorial

What's hot (20)

PPT
java jdbc connection
PPT
3 database-jdbc(1)
PDF
Jdbc[1]
PPT
Java jdbc
PPTX
DataBase Connectivity
PDF
Introduction to JDBC and database access in web applications
PPT
PPTX
Database Access With JDBC
PPTX
Java database connectivity
PPS
Jdbc api
PPT
Java Database Connectivity
PDF
PPTX
Java database connectivity with MySql
PPTX
Jdbc in servlets
PPTX
Lecture 1. java database connectivity
PPTX
PPT
Jdbc ppt
PPT
Jdbc
PPTX
jsp MySQL database connectivity
java jdbc connection
3 database-jdbc(1)
Jdbc[1]
Java jdbc
DataBase Connectivity
Introduction to JDBC and database access in web applications
Database Access With JDBC
Java database connectivity
Jdbc api
Java Database Connectivity
Java database connectivity with MySql
Jdbc in servlets
Lecture 1. java database connectivity
Jdbc ppt
Jdbc
jsp MySQL database connectivity
Ad

Viewers also liked (19)

PPS
Jdbc architecture and driver types ppt
PPSX
JDBC: java DataBase connectivity
PPTX
Java Database Connectivity (JDBC)
PDF
3. Curso Java JDBC (Bases de datos) - Curso 2005-2006
DOC
Data warehouse-dimensional-modeling-and-design
ODP
Dimensional Modelling
PPT
Networking Java Socket Programming
PPTX
Network programming in java - PPT
PPT
Network programming in Java
PPT
Java y Bases de Datos
PPTX
Dimensional Modeling Basic Concept with Example
PPT
Ppt of socket
DOC
Difference between ER-Modeling and Dimensional Modeling
PDF
Curso Básico de JDBC
PPT
Data Warehouse Modeling
PDF
Data Warehouse Design and Best Practices
Jdbc architecture and driver types ppt
JDBC: java DataBase connectivity
Java Database Connectivity (JDBC)
3. Curso Java JDBC (Bases de datos) - Curso 2005-2006
Data warehouse-dimensional-modeling-and-design
Dimensional Modelling
Networking Java Socket Programming
Network programming in java - PPT
Network programming in Java
Java y Bases de Datos
Dimensional Modeling Basic Concept with Example
Ppt of socket
Difference between ER-Modeling and Dimensional Modeling
Curso Básico de JDBC
Data Warehouse Modeling
Data Warehouse Design and Best Practices
Ad

Similar to JDBC Basics (In 20 Minutes Flat) (20)

PDF
Jdbc tutorial
PPTX
Java Database Connectivity (JDBC) ppt by Aamir Rafique.pptx
PPTX
Jdbc
DOCX
Db examples
PDF
PDF
Advance Java Practical file
PDF
JDBC programming
PDF
Lecture17
PPT
JDBC.ppt
PPTX
Jdbc presentation
PPT
Web based development
PDF
Simple Jdbc With Spring 2.5
PPTX
Module 5 jdbc.ppt
PDF
PDF
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdf
DOCX
This is a basic JAVA pgm that contains all of the major compoents of DB2
PPTX
Database Programming Techniques
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
PDF
Jdbc 1
DOC
Java database connectivity notes for undergraduate
Jdbc tutorial
Java Database Connectivity (JDBC) ppt by Aamir Rafique.pptx
Jdbc
Db examples
Advance Java Practical file
JDBC programming
Lecture17
JDBC.ppt
Jdbc presentation
Web based development
Simple Jdbc With Spring 2.5
Module 5 jdbc.ppt
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdf
This is a basic JAVA pgm that contains all of the major compoents of DB2
Database Programming Techniques
Java OOP Programming language (Part 8) - Java Database JDBC
Jdbc 1
Java database connectivity notes for undergraduate

More from Craig Dickson (16)

PPTX
Amazon Webservices for Java Developers - UCI Webinar
PPTX
Dead-Simple Deployment: Headache-Free Java Web Applications in the Cloud
PPTX
Rapid RESTful Web Applications with Apache Sling and Jackrabbit
PPTX
Java PaaS Vendor Survey - September 2011
PPT
How to test drive development using Linux
PPT
Google Wave Introduction
PPT
Adobe Flex 4 Overview
PPT
Palm WebOS Overview
PPT
Java Persistence API (JPA) - A Brief Overview
PPT
eHarmony in the Cloud
PPT
Fast and Free SSO: A Survey of Open-Source Solutions to Single Sign-on
PPT
Building Social Applications using Zembly
PPT
Best Practices for Large-Scale Web Sites
PPT
Cloud Computing Introduction
PPT
Performance Analysis and Monitoring with Perf4j
PPT
JavaFX vs AJAX vs Flex
Amazon Webservices for Java Developers - UCI Webinar
Dead-Simple Deployment: Headache-Free Java Web Applications in the Cloud
Rapid RESTful Web Applications with Apache Sling and Jackrabbit
Java PaaS Vendor Survey - September 2011
How to test drive development using Linux
Google Wave Introduction
Adobe Flex 4 Overview
Palm WebOS Overview
Java Persistence API (JPA) - A Brief Overview
eHarmony in the Cloud
Fast and Free SSO: A Survey of Open-Source Solutions to Single Sign-on
Building Social Applications using Zembly
Best Practices for Large-Scale Web Sites
Cloud Computing Introduction
Performance Analysis and Monitoring with Perf4j
JavaFX vs AJAX vs Flex

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
1. Introduction to Computer Programming.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
A Presentation on Artificial Intelligence
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Mushroom cultivation and it's methods.pdf
PDF
Getting Started with Data Integration: FME Form 101
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Spectroscopy.pptx food analysis technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
1. Introduction to Computer Programming.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Building Integrated photovoltaic BIPV_UPV.pdf
cloud_computing_Infrastucture_as_cloud_p
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Encapsulation_ Review paper, used for researhc scholars
Advanced methodologies resolving dimensionality complications for autism neur...
A Presentation on Artificial Intelligence
TLE Review Electricity (Electricity).pptx
Mushroom cultivation and it's methods.pdf
Getting Started with Data Integration: FME Form 101
Reach Out and Touch Someone: Haptics and Empathic Computing
Spectroscopy.pptx food analysis technology

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 !
  • 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 !

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