SlideShare ist ein Scribd-Unternehmen logo
1 von 18
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?


!

Weitere ähnliche Inhalte

Was ist angesagt? (20)

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
Jdbc
JdbcJdbc
Jdbc
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Jdbc
JdbcJdbc
Jdbc
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
JDBC
JDBCJDBC
JDBC
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc
JdbcJdbc
Jdbc
 
jsp MySQL database connectivity
jsp MySQL database connectivityjsp MySQL database connectivity
jsp MySQL database connectivity
 

Andere mochten auch

Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
3. Curso Java JDBC (Bases de datos) - Curso 2005-2006
3. Curso Java JDBC (Bases de datos) - Curso 2005-20063. Curso Java JDBC (Bases de datos) - Curso 2005-2006
3. Curso Java JDBC (Bases de datos) - Curso 2005-2006Samuel Marrero
 
Data warehouse-dimensional-modeling-and-design
Data warehouse-dimensional-modeling-and-designData warehouse-dimensional-modeling-and-design
Data warehouse-dimensional-modeling-and-designSarita Kataria
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Java y Bases de Datos
Java y Bases de DatosJava y Bases de Datos
Java y Bases de DatosRonny Parra
 
Dimensional Modeling Basic Concept with Example
Dimensional Modeling Basic Concept with ExampleDimensional Modeling Basic Concept with Example
Dimensional Modeling Basic Concept with ExampleSajjad Zaheer
 
Difference between ER-Modeling and Dimensional Modeling
Difference between ER-Modeling and Dimensional ModelingDifference between ER-Modeling and Dimensional Modeling
Difference between ER-Modeling and Dimensional ModelingAbdul Aslam
 
Data Warehouse Modeling
Data Warehouse ModelingData Warehouse Modeling
Data Warehouse Modelingvivekjv
 
Data Warehouse Design and Best Practices
Data Warehouse Design and Best PracticesData Warehouse Design and Best Practices
Data Warehouse Design and Best PracticesIvo Andreev
 

Andere mochten auch (19)

Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
3. Curso Java JDBC (Bases de datos) - Curso 2005-2006
3. Curso Java JDBC (Bases de datos) - Curso 2005-20063. Curso Java JDBC (Bases de datos) - Curso 2005-2006
3. Curso Java JDBC (Bases de datos) - Curso 2005-2006
 
Data warehouse-dimensional-modeling-and-design
Data warehouse-dimensional-modeling-and-designData warehouse-dimensional-modeling-and-design
Data warehouse-dimensional-modeling-and-design
 
Dimensional Modelling
Dimensional ModellingDimensional Modelling
Dimensional Modelling
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Java y Bases de Datos
Java y Bases de DatosJava y Bases de Datos
Java y Bases de Datos
 
Dimensional Modeling Basic Concept with Example
Dimensional Modeling Basic Concept with ExampleDimensional Modeling Basic Concept with Example
Dimensional Modeling Basic Concept with Example
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Difference between ER-Modeling and Dimensional Modeling
Difference between ER-Modeling and Dimensional ModelingDifference between ER-Modeling and Dimensional Modeling
Difference between ER-Modeling and Dimensional Modeling
 
Curso Básico de JDBC
Curso Básico de JDBCCurso Básico de JDBC
Curso Básico de JDBC
 
Data Warehouse Modeling
Data Warehouse ModelingData Warehouse Modeling
Data Warehouse Modeling
 
Data Warehouse Design and Best Practices
Data Warehouse Design and Best PracticesData Warehouse Design and Best Practices
Data Warehouse Design and Best Practices
 

Ähnlich wie JDBC Basics (In 20 Minutes Flat)

Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programmingchanwook Park
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2Sheila A. Bell, MS, PMP
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 

Ähnlich wie JDBC Basics (In 20 Minutes Flat) (20)

Jdbc
JdbcJdbc
Jdbc
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Lecture17
Lecture17Lecture17
Lecture17
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 

Mehr von Craig Dickson

Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarCraig Dickson
 
Dead-Simple Deployment: Headache-Free Java Web Applications in the Cloud
Dead-Simple Deployment: Headache-Free Java Web Applications in the CloudDead-Simple Deployment: Headache-Free Java Web Applications in the Cloud
Dead-Simple Deployment: Headache-Free Java Web Applications in the CloudCraig Dickson
 
Rapid RESTful Web Applications with Apache Sling and Jackrabbit
Rapid RESTful Web Applications with Apache Sling and JackrabbitRapid RESTful Web Applications with Apache Sling and Jackrabbit
Rapid RESTful Web Applications with Apache Sling and JackrabbitCraig Dickson
 
Java PaaS Vendor Survey - September 2011
Java PaaS Vendor Survey - September 2011Java PaaS Vendor Survey - September 2011
Java PaaS Vendor Survey - September 2011Craig Dickson
 
How to test drive development using Linux
How to test drive development using LinuxHow to test drive development using Linux
How to test drive development using LinuxCraig Dickson
 
Google Wave Introduction
Google Wave IntroductionGoogle Wave Introduction
Google Wave IntroductionCraig Dickson
 
Adobe Flex 4 Overview
Adobe Flex 4 OverviewAdobe Flex 4 Overview
Adobe Flex 4 OverviewCraig Dickson
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewCraig Dickson
 
eHarmony in the Cloud
eHarmony in the CloudeHarmony in the Cloud
eHarmony in the CloudCraig Dickson
 
Fast and Free SSO: A Survey of Open-Source Solutions to Single Sign-on
Fast and Free SSO: A Survey of Open-Source Solutions to Single Sign-onFast and Free SSO: A Survey of Open-Source Solutions to Single Sign-on
Fast and Free SSO: A Survey of Open-Source Solutions to Single Sign-onCraig Dickson
 
Building Social Applications using Zembly
Building Social Applications using ZemblyBuilding Social Applications using Zembly
Building Social Applications using ZemblyCraig Dickson
 
Best Practices for Large-Scale Web Sites
Best Practices for Large-Scale Web SitesBest Practices for Large-Scale Web Sites
Best Practices for Large-Scale Web SitesCraig Dickson
 
Cloud Computing Introduction
Cloud Computing IntroductionCloud Computing Introduction
Cloud Computing IntroductionCraig Dickson
 
Performance Analysis and Monitoring with Perf4j
Performance Analysis and Monitoring with Perf4jPerformance Analysis and Monitoring with Perf4j
Performance Analysis and Monitoring with Perf4jCraig Dickson
 
JavaFX vs AJAX vs Flex
JavaFX vs AJAX vs FlexJavaFX vs AJAX vs Flex
JavaFX vs AJAX vs FlexCraig Dickson
 

Mehr von Craig Dickson (16)

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

Kürzlich hochgeladen

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 

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 !

Hinweis der Redaktion

  1. - Good afternoon\n\n- We’re going to take a quick look at the basic elements that make up JDBC\n
  2. - 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
  3. - 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
  4. - 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
  5. - 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
  6. - 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
  7. - 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
  8. - 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
  9. - 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
  10. - 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
  11. - 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
  12. - 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
  13. - 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
  14. - 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
  15. - 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
  16. \n
  17. \n
  18. \n