JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Slides:



Advertisements
Similar presentations
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Advertisements

JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
JDBC CS-328. JDBC Java API for accessing RDBMS Allows use of SQL for RDBMS programming Can be used for: –embedded SQL –execution of stored queries.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
CSE470 Software Engineering Fall Database Access through Java.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
What is JDBC? Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. provides.
Database Programming in Java Corresponds with Chapter 32, 33.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
JDBC – Java Database Concentricity
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Session 30 Basics of JDBC. Java Simplified / Session 30 / 2 of 33 Review A Swing menu consists of a menubar, menuitems and menus. Trees are used to depict.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Basics of JDBC Session 14.
JDBC (Java Database Connectivity)
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
DEPTT. OF COMP. SC & APPLICATIONS
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
Java Access to RDB Relational databases (RDBs) dominate today, due to:
JDBC Database Management Database connectivity
Design and Implementation of Software for the Web
Objectives In this lesson, you will learn about:
Interacting with Database
JDBC – ODBC DRIVERS.
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1

Basic Idea Use JDBC to connect to a relational database and perform standard SQL queries to read and write data Low-level Java interface for SQL commands based on ODBC Related Concepts: –SQL –ODBC Contained in two packages –java.sql –javax.sql ©SoftMoore ConsultingSlide 2

JDBC Advantages Allows a pure-Java connection to a database –All programming remains in Java domain, with full access to Java features –Automatic conversion between SQL types and Java types Cross-platform and database independent –Code with any database for which there is a JDBC driver Can access virtually any data source –relational database –spreadsheet –text file ©SoftMoore ConsultingSlide 3

Objectives Use JDBC to connect to a relational database Execute SQL queries on the database Handle the results of a query View the structure of a database using metadata Understand JDBC exceptions and warnings ©SoftMoore ConsultingSlide 4

Alternatives/Related Technology Hibernate Java Data Objects (JDO) TopLink EJB3 Java Persistence API (JPA) Serialization ©SoftMoore ConsultingSlide 5

Using JDBC ©SoftMoore ConsultingSlide 6 JDBC/ODBC Bridge ODBC Driver Vendor- supplied JDBC Driver Database JDBC API JDBC Driver API Java Application using JDBC JDBC Driver Manager

JDBC Driver Types Type 1: JDBC-ODBC Bridge plus ODBC –relies on a local ODBC driver to access database –Oracle provides a JDBC-ODBC bridge –not usually suitable for production use Type 2: Native-API Partly-Java –converts JDBC calls to native database API calls of local driver –requires that some platform-specific binary code be loaded on each client machine ©SoftMoore ConsultingSlide 7

JDBC Driver Types (continued) Type 3: JDBC-Net Pure Java –translates JDBC calls to database-neutral protocol to communicate with a Java application server –server converts requests to connect its pure Java clients to many different databases –most flexible alternative Type 4: Native-Protocol Pure Java –converts JDBC calls directly into database-specific protocol ©SoftMoore ConsultingSlide 8

Vendor Support Most database vendors supply type 3 and type 4 drivers. List of companies supporting JDBC List of available JDBC drivers ©SoftMoore ConsultingSlide 9

ODBC Data Sources Databases accessed through ODBC are called data sources. Various kinds of ODBC data sources –relational databases –spreadsheets –text files Each ODBC data source must have an ODBC driver. The ODBC driver for the data source acts as a server to handle requests from ODBC clients. ©SoftMoore ConsultingSlide 10

Creating a Data Source in Windows The ODBC Data Source Dialog ©SoftMoore ConsultingSlide 11

SQL Conformance Databases differ on how they implement advanced SQL features. JDBC allows any string to be passed to driver, allowing access to non-standard advanced features. JDBC drivers and ODBC drivers accessed through the JDBC-ODBC bridge may have different conformance levels. ©SoftMoore ConsultingSlide 12

SQL Conformance: JDBC Drivers Not all JDBC drivers support latest ANSI SQL grammar. All JDBC-compliant drivers support Entry Level SQL. Use DatabaseMetaData object methods to determine conformance level: –supportsANSI92EntryLevelSQL() –supportsANSI92IntermediateSQL() –supportsANSI92FullSQL() ©SoftMoore ConsultingSlide 13

Using JDBC with Applets Problem: How to allow applets to access databases Issues: –Distribution (want to avoid binaries) –Security Solution: use three-tier approach: Applet ↔ server ↔ database –applet uses a socket connection to the web host to send database requests to an intermediate server –server receives the request and spawns a thread to handle the database connection –server returns the results to the applet ©SoftMoore ConsultingSlide 14

Basic Steps in Using JDBC Load a JDBC driver Connect to the data source Execute SQL statements Process query results Commit or rollback database changes Close the connection ©SoftMoore ConsultingSlide 15

The JDBC Driver Manager Management layer of JDBC When a Driver class is loaded, it registers itself with the DriverManager. The DriverManager maintains list of all drivers that have registered. Multiple drivers can be loaded/registered. The DriverManager automatically determines which driver to use for a connection. ©SoftMoore ConsultingSlide 16

Loading a Driver Using method Class.forName() String driverName = "oracle.jdbc.driver.OracleDriver"; Class.forName(driverName); From the property jdbc.drivers –from the command-line java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver JavaProgram –from within the application System.setProperty("jdbc.drivers", "oracle.jdbc.driver.OracleDriver"); By creating an instance with a constructor –(not recommended) new oracle.jdbc.driver.OracleDriver(); ©SoftMoore ConsultingSlide 17

DriverManager.setLogWriter() The PrintWriter where the driver manager sends trace messages. By default, the PrintWriter used for logging is set to null (disabled). To watch log messages use PrintWriter pw = new PrintWriter(System.out); DriverManager.setLogWriter(pw); ©SoftMoore ConsultingSlide 18

Connecting Uses a JDBC URL of the form jdbc: : where jdbc is the protocol is the name of the driver or the database connectivity mechanism is a driver-specific name that identifies the data source (database) ©SoftMoore ConsultingSlide 19

Example: Making a Connection String url = "jdbc:derby:Accounts"; String user = "dba"; String pw = "Hello"; Connection conn = DriverManager.getConnection(url, user, pw); ©SoftMoore ConsultingSlide 20 Note: getConnection() throws a SQLException on failure to connect.

JDBC Statements Method DriverManager.getConnection() returns a Connection object. Use Connection.createStatement() to create Statement objects. Use Statement objects to execute SQL commands. Results of a query will held in ResultSet objects. ©SoftMoore ConsultingSlide 21

Three Kinds of JDBC Statements ©SoftMoore ConsultingSlide 22 «interface» Statement «interface» CallableStatement «interface» PreparedStatement Simple SQL statement with no parameters Precompiled SQL statement (may have input parameters) Used to execute database stored procedures

Statement Execute Methods JDBC statements send SQL commands by using one of three execute methods defined in the Statement interface. The method to use depends on the result of the statement: –executeQuery() is used for SELECT –executeUpdate() is used for INSERT, UPDATE, DELETE, CREATE TABLE, etc. –execute() is used rarely for very special cases ©SoftMoore ConsultingSlide 23

Statement.executeQuery() Used when there will be one ResultSet Represents a table of results The SQL query is passed as a String argument. ©SoftMoore ConsultingSlide 24

ResultSet Maintains a row cursor for iterating forward through the rows of the result table Initial position of cursor is before the first row The next() method –moves the cursor to the next row of the result table –returns true while there are more rows in the result ©SoftMoore ConsultingSlide 25

Example: Book Schema ©SoftMoore ConsultingSlide 26 publisher_id name url publisher book_id title isbn publisher_id book book_id author_id seq_num book_author author_id last_name first_name author

Executing a Query String query = "select * from book order by title"; Connection conn = DriverManager.getConnection(url, user, pw); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) {... } ©SoftMoore ConsultingSlide 27

GetXXX() Methods The ResultSet objects have getXXX() methods to get the values of each column in a row of data Different getXXX() method for each supported data type; e.g., getInt(), getString(),... Can refer to columns by name or number Warning: first column has number 1, not 0! ©SoftMoore ConsultingSlide 28

Examples: GetXXX() Methods int bookId = rs.getInt("book_id"); int bookId = rs.getInt(1); // same as above String title = rs.getString("title"); String isbn = rs.getString("isbn"); ©SoftMoore ConsultingSlide 29

Java-SQL Type Equivalence ©SoftMoore ConsultingSlide 30 Java MethodSQL Type boolean getBoolean()BIT short getShort()SMALLINT int getInt()INTEGER long getLong()BIGINT float getFloat()REAL double getDouble() FLOAT DOUBLE

Java-SQL Type Equivalence (continued) ©SoftMoore ConsultingSlide 31 Java MethodSQL Type BigDecimal getBigDecimal() NUMERIC DECIMAL String getString() CHAR VARCHAR byte[] getBytes() BINARY VARBINARY Object getObject()any type

Java-SQL Type Equivalence (continued) ©SoftMoore ConsultingSlide 32 Java MethodSQL Type Clob getClob()CLOB Blob getBlob()BLOB Date getDate()DATE Time getTime()TIME Timestamp getTimeStamp()TIMESTAMP Classes Blob, Clob, Date, Time, and Timestamp are defined in package java.sql.

Java Strings and SQL CHARS SQL types CHAR, VARCHAR, and LONGVARCHAR all map to Java strings. Fixed-length SQL strings ( CHAR(n) ) are padded to length n during conversion to Java strings. The same padding occurs when converting Java strings to SQL fixed-length strings. ©SoftMoore ConsultingSlide 33

Getting LONGVARCHAR as Java Streams When retrieving large strings of type LONGVARCHAR, the ResultSet methods –getAsciiStream() and –getUnicodeStream() can be used to get the value as a stream. ©SoftMoore ConsultingSlide 34

Binary SQL Values As with SQL strings, SQL binary types, BINARY, VARBINARY, and LONGVARBINARY are all mapped to Java byte[] objects The ResultSet method getBinaryStream() can be used to read large binary objects ( LONGVARBINARY ) ©SoftMoore ConsultingSlide 35

Example: List Books by James Rumbaugh String query = "select b.title" + " from book b, book_author ba, author a" + " where b.book_id = ba.book_id" + " and ba.author_id = a.author_id" + " and a.first_name = 'James'" + " and a.last_name = 'Rumbaugh'" + " order by title"; ConnectionFactory factory = ConnectionFactory.getInstance(); Connection conn = factory.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); System.out.println("Books by James Rumbaugh"); while (rs.next()) System.out.println("- " + rs.getString("title")); ©SoftMoore ConsultingSlide 36

Statement.executeUpdate() Used for INSERT, UPDATE, or DELETE statements Also used for SQL data definition statements like CREATE TABLE and ALTER TABLE Return value is number of rows modified (there is no ResultSet object) ©SoftMoore ConsultingSlide 37

Example: Inserting Data static String[] sqlInserts = { "insert into author values (1000, 'Gamma', 'Erich')", "insert into author values (1001, 'Helm', 'Richard')", "insert into author values (1002, 'Johnson', 'Ralph')",... } int updateCount = 0; for (int i = 0; i < sqlInserts.length; ++i) updateCount += stmt.executeUpdate(sqlInserts[i]); ©SoftMoore ConsultingSlide 38

Additional Update Examples // create table with name and height columns stmt.executeUpdate("create table Data " + "(name varchar(30), height integer)"); // inserting data stmt.executeUpdate("insert into Data " + "values ('John', 68)"); // updating data stmt.executeUpdate("update Data" + " set height = 70" + " where name = 'John'"); // deleting data stmt.executeUpdate("delete from Data" + " where name = 'John'"); ©SoftMoore ConsultingSlide 39

Statement.execute() Used for cases when the statement might –return more than one ResultSet –return more than one update count (number of rows modified) –return a combination of both Can always be used if programmer is unsure of the result Example: A stored procedure may execute multiple statements, each of which will have a result. ©SoftMoore ConsultingSlide 40

Retrieving Results From Statement.execute() Method Statement.execute() returns a boolean –true if next result is a ResultSet –false if next result is an update count –false if there are no more results Use Statement.getResultSet() to get the current result as a ResultSet object Use Statement.getMoreResults() to move to the next result Use Statement.getUpdateCount() to get the current result as an update count ©SoftMoore ConsultingSlide 41

Multiple Result Sets In Practice Not common Used primarily when the programmer usually knows what to expect, either from database or stored procedure documentation Might not be supported by the database. ©SoftMoore ConsultingSlide 42

Closing the Connection Ensures that system resources are freed conn.close(); Can also close –Statement objects closed automatically when the connection is closed –ResultSet objects closed automatically when the statement is closed ©SoftMoore ConsultingSlide 43