CS6320 - JDBC Introducing JDBC JDBC: is an API that provides “universal data access for the Java2 platform” Allows you to connect to a known data source.

Slides:



Advertisements
Similar presentations
1 Introduction to JDBC. 2 Road Map  Introduction to JDBC/JDBC Drivers  Overview: Six Steps to using JDBC  Example 1: Setting up Tables via JDBC  Example.
Advertisements

Database programming in Java An introduction to Java Database Connectivity (JDBC)
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 PostgreSQL JDBC interface documentation
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.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 JDBC Java Database Connectivity. 2 c.pdf
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 Pointbase Developer Manual.
1 JDBC: Part I Attribution These slides are based on three primary sources: –Sun JDBC Tutorial URL: jdbc/TOC.htmlhttp://java.sun.com/docs/books/tutorial/
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.
Lecture 2 Introduction to JDBC. Introducing JDBC 4 According to Sun, JDBC is not an acronym, but is commonly misinterpreted to mean Java DataBase Connectivity.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Objectives Describe JDBC Describe JDBC Driver Types
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.
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
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.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
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 (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
Introduction to JDBC Michelle Lee, Ye Wu & Jeff Offutt SWE 432 Design and Implementation of Software for the Web.
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 – Java DataBase Connectivity. JDBC API Overview JDBC is Java API that allows the Java programmers to access database management system from Java.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Lecture 2 Introduction to JDBC. Introducing JDBC  According to Sun, JDBC is not an acronym, but is commonly misinterpreted to mean Java DataBase Connectivity.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
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.
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.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
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.
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)
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
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.
1 JDBC – Java Database Connectivity CS , Spring 2010.
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.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
CS JDBC.
Interacting with Database
JAVA Connection The following uses a ‘bridge’ between Java Database Connectivity (JDBC) and ODBC, namely sun.jdbc.odbc.JdbcOdbcDriver Supplied with the.
HW#4 Making Simple BBS Using JDBC
Objectives In this lesson, you will learn about:
Interacting with Database
Lecture 2 Introduction to JDBC.
JDBC Example.
Presentation transcript:

CS JDBC

Introducing JDBC JDBC: is an API that provides “universal data access for the Java2 platform” Allows you to connect to a known data source using common OO semantics using Java JDBC: is an API that provides “universal data access for the Java2 platform” Allows you to connect to a known data source using common OO semantics using Java Allows you to issue standard SQL commands on that data source Allows you to issue standard SQL commands on that data source Provides you with classes to facilitate access to and manipulation of: Provides you with classes to facilitate access to and manipulation of: returned data and,returned data and, generated exceptionsgenerated exceptions

JDBC Driver Types Type 1 (JDBC-ODBC Bridge Technology) Type 1 (JDBC-ODBC Bridge Technology) Type 2 (JNI drivers for native connection libraries) Type 2 (JNI drivers for native connection libraries) Type 3 (Socket-level Middleware Translator) Type 3 (Socket-level Middleware Translator) Type 4 (Pure Java-DBMS driver) Type 4 (Pure Java-DBMS driver)

Driver Types Type 1 Type 2 Type 3Type 4

Type 1 Drivers: JDBC-ODBC Bridges JDBC driver translates call into ODBC and redirects ODBC call to an ODBC driver on the DBMS JDBC driver translates call into ODBC and redirects ODBC call to an ODBC driver on the DBMS ODBC binary code must exist on every client ODBC binary code must exist on every client Translation layer compromises execution speed to small degree Translation layer compromises execution speed to small degree

Type 2 Drivers: Native-API + Java Driver Java driver makes JNI calls on the client API (usually written in C or C++) Java driver makes JNI calls on the client API (usually written in C or C++) eg: Sybase dblib or ctlibeg: Sybase dblib or ctlib eg: Oracle Call Interface libs (OCI)eg: Oracle Call Interface libs (OCI) Requires client-side code to be installed Requires client-side code to be installed Often the fastest solution available Often the fastest solution available Native drivers are usually delivered by DBMS vendor Native drivers are usually delivered by DBMS vendor Bug in driver can crash JVMs Bug in driver can crash JVMs

Type 3 Drivers: JDBC-Middleware Pure Java Driver JDBC driver translates JDBC calls into a DBMS-independent protocol JDBC driver translates JDBC calls into a DBMS-independent protocol Then, communicates over a socket with a middleware server that translates Java code into native API DBMS calls Then, communicates over a socket with a middleware server that translates Java code into native API DBMS calls No client code need be installed No client code need be installed Single driver provides access to multiple DBMSs, eg. WebLogic, Tengah drivers Single driver provides access to multiple DBMSs, eg. WebLogic, Tengah drivers Type 3 drivers auto-download for applets. Type 3 drivers auto-download for applets. Communication is indirect via a middleware server Communication is indirect via a middleware server

Type 4 Drivers: Pure Java Drivers Java drivers talk directly to the DBMS using Java sockets Java drivers talk directly to the DBMS using Java sockets No Middleware layer needed, access is direct. No Middleware layer needed, access is direct. Simplest solution available. Simplest solution available. No client code need be installed. No client code need be installed. Type 4 drivers auto-download for applets Type 4 drivers auto-download for applets

JDBC Drivers JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL. JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL.

Six Steps to Using JDBC (simple program…no connection pooling/middleware) 1. Load the JDBC Driver 2. Establish the Database Connection 3. Create a Statement Object 4. Execute a Query 5. Process the Results 6. Close the Connection

A standard simple JDBC application // Load the JDBC driver Class.forName("oracle.jdbc.OracleDriver").newInstance(); // Connect to the database Connection conn = DriverManager.getConnection (connect-string,user, pass); // Create a statement Statement stmt = conn.createStatement (); Statement stmt = conn.createStatement (); // Execute the statement: select data from the emp table boolean results = stmt.execute("select * from emp"); boolean results = stmt.execute("select * from emp"); ResultSet rset = null; ResultSet rset = null; if (results) rset = stmt.getResultSet(); if (results) rset = stmt.getResultSet(); // Process results: walk through the result set while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2)); System.out.println (rset.getString (1) + rset.getString(2)); …. ….}

Overview: Connecting to a Database // Load the Oracle JDBC driver Class.forName("oracle.jdbc.OracleDriver").newInstance(); // Connect to the database Connection conn = DriverManager.getConnection (connect-string,user, pass); // Create a statement Statement stmt = conn.createStatement (); Statement stmt = conn.createStatement (); // Select data from the emp table boolean results = stmt.execute("select * from emp"); boolean results = stmt.execute("select * from emp"); ResultSet rset = null; ResultSet rset = null; if (results) rset = stmt.getResultSet(); if (results) rset = stmt.getResultSet(); // Walk through the result set while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2)); System.out.println (rset.getString (1) + rset.getString(2)); …. ….}

The JDBC Driver Manager Management layer of JDBC, interfaces between the client and the driver. Management layer of JDBC, interfaces between the client and the driver. Keeps a list of available driversKeeps a list of available drivers Manages driver login time limits and printing of log and tracing messagesManages driver login time limits and printing of log and tracing messages Secure because manager will only allow drivers that come from local file system or the same initial class loader requesting a connection Secure because manager will only allow drivers that come from local file system or the same initial class loader requesting a connection Most popular use: Most popular use: Connection getConnection(url, id, passwd);Connection getConnection(url, id, passwd);

Create a Connection to the database Call the getConnection method on the DriverManager. Call the getConnection method on the DriverManager. Connection conn = DriverManager.getConnection(url, login, password) DriverManager.getConnection(url, login, password) URLs: URLs: “jdbc:sybase:Tds:skunk:4100/myDB”“jdbc:sybase:Tds:skunk:4100/myDB” du:1521:cs51024"; Only one requirement: the relevant Drivers must be able to recognize their own URL Only one requirement: the relevant Drivers must be able to recognize their own URL

Overview: Statements // Load the Oracle JDBC driver Class.forName("oracle.jdbc.OracleDriver").newInstance(); // Connect to the database Connection conn = DriverManager.getConnection (connect-string,user, pass); // Create a statement Statement stmt = conn.createStatement (); Statement stmt = conn.createStatement (); // Select data from the emp table boolean results = stmt.execute("select * from emp"); boolean results = stmt.execute("select * from emp"); ResultSet rset = null; ResultSet rset = null; if (results) rset = stmt.getResultSet(); if (results) rset = stmt.getResultSet(); // Walk through the result set while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2)); System.out.println (rset.getString (1) + rset.getString(2)); …. ….}

SQL Statements Types of statements: Class Statement Class Statement Represents a basic SQL statementRepresents a basic SQL statement Statement stmt = conn.createStatement();Statement stmt = conn.createStatement(); Class PreparedStatement Class PreparedStatement A precompiled SQL statement, which can offer improved performance, especially for large/complex SQL statementsA precompiled SQL statement, which can offer improved performance, especially for large/complex SQL statements Class CallableStatement Class CallableStatement Allows JDBC programs access to stored proceduresAllows JDBC programs access to stored procedures Can be used for both DDL and DML commands

Execute an SQL Statement executeQuery(): execute a query and get a ResultSet back executeQuery(): execute a query and get a ResultSet back executeUpdate(): execute an update and get back an int specifying number of rows acted on executeUpdate(): execute an update and get back an int specifying number of rows acted on UPDATE [table] set [column_name] = value where […]UPDATE [table] set [column_name] = value where […] DELETE from [table] where [column_name] = 5DELETE from [table] where [column_name] = 5 execute(): exec. unknown SQL, returns true if a resultSet is available: execute(): exec. unknown SQL, returns true if a resultSet is available: Statement genericStmt = conn.createStatement(); if( genericStmt.execute(SQLString)) { ResultSet rs = genericStmt.getResultSet(); process(); } else { int updated = genericStmt.getUpdateCount(); processCount();}…

Prepared Statements Use for complex queries or repeated queries Use for complex queries or repeated queries Features: Features: precompiled at database (statement usually sent to database immediately on creation for compilation)precompiled at database (statement usually sent to database immediately on creation for compilation) supply with new variables each time you call itsupply with new variables each time you call it Example: Example: PreparedStatement ps = conn.prepareStatement(“update table set sales = ? Where custName = ?”);PreparedStatement ps = conn.prepareStatement(“update table set sales = ? Where custName = ?”); Set with values (use setXXX() methods on PreparedStatement: Set with values (use setXXX() methods on PreparedStatement: ps.setInt(1, );ps.setInt(1, ); ps.setString(2, “United Airlines”);ps.setString(2, “United Airlines”); Then execute: Then execute: int count = ps.executeUpdate();int count = ps.executeUpdate();

Overview: ResultSets and Cursors // Load the Oracle JDBC driver Class.forName("oracle.jdbc.OracleDriver").newInstance(); // Connect to the database Connection conn = DriverManager.getConnection (connect-string,user, pass); // Create a statement Statement stmt = conn.createStatement (); Statement stmt = conn.createStatement (); // Select data from the emp table boolean results = stmt.execute("select * from emp"); boolean results = stmt.execute("select * from emp"); ResultSet rset = null; ResultSet rset = null; if (results) rset = stmt.getResultSet(); if (results) rset = stmt.getResultSet(); // Walk through the result set while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2)); System.out.println (rset.getString (1) + rset.getString(2)); …. ….}

Result Sets and Cursors Result Sets are returned from queries. Result Sets are returned from queries. Possible number of rows: zero, one, or more Possible number of rows: zero, one, or more Cursors are ‘iterators’ that can be user to ‘walk’ through a result set Cursors are ‘iterators’ that can be user to ‘walk’ through a result set JDBC 2.0 allows for backward as well as forward cursors, including the ability to go to a specific row or a relative row JDBC 2.0 allows for backward as well as forward cursors, including the ability to go to a specific row or a relative row

Result Sets Iterate over all rows: Iterate over all rows: ResultSet rs = stmt.executeQuery(“select id, price from inventory”);ResultSet rs = stmt.executeQuery(“select id, price from inventory”); rs.next(), rs.previous(), rs.first(), …rs.next(), rs.previous(), rs.first(), … call once to access first row: while(rs.next()) {} call once to access first row: while(rs.next()) {} Extract data from the ResultSet Extract data from the ResultSet getXXX(columnName/indexVal)getXXX(columnName/indexVal) getInt() getInt() getDouble() getDouble() getString() (highly versatile, inclusive of others; automatic conversion to String for most types) getString() (highly versatile, inclusive of others; automatic conversion to String for most types) getObject() (returns a generic Java Object) getObject() (returns a generic Java Object) rs.wasNull() - returns true if last get was Nullrs.wasNull() - returns true if last get was Null

Example : Inserting Data via JDBC

import java.sql.*; public class InsertCoffees { public static void main(String args[]) throws SQLException { System.out.println ("Adding Coffee Data"); ResultSet rs = null; PreparedStatement ps = null; String url = "jdbc:mysql://localhost/cerami"; Connection con; Statement stmt; try { Class.forName("org.gjt.mm.mysql.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } 1

try { con = DriverManager.getConnection(url); stmt = con.createStatement(); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)"); stmt.close(); con.close(); System.out.println ("Done"); } catch(SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); }

Example : Querying Data via JDBC

import java.sql.*; public class SelectCoffees { public static void main(String args[]) throws SQLException { ResultSet rs = null; PreparedStatement ps = null; String url = "jdbc:mysql://localhost/cerami"; Connection con; Statement stmt; try { Class.forName("org.gjt.mm.mysql.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url); stmt = con.createStatement(); 1 2 3

ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); System.out.println("Table COFFEES:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } 4 5 6

Exception Handling SQL Exceptions SQL Exceptions Nearly every JDBC method can throw a SQLException in response to a data access errorNearly every JDBC method can throw a SQLException in response to a data access error If more than one error occurs, they are chained togetherIf more than one error occurs, they are chained together SQL exceptions contain:SQL exceptions contain: Description of the error, getMessage Description of the error, getMessage The SQLState (Open Group SQL specification) identifying the exception, getSQLState The SQLState (Open Group SQL specification) identifying the exception, getSQLState A vendor-specific integer, error code, getErrorCode A vendor-specific integer, error code, getErrorCode A chain to the next SQLException, getNextException A chain to the next SQLException, getNextException

SQL Exception Example try {... // JDBC statement.... // JDBC statement. } catch (SQLException sqle) { while (sqle != null) { while (sqle != null) { System.out.println("Message: " + sqle.getMessage()); System.out.println("Message: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("Vendor Error: " + System.out.println("Vendor Error: " + sqle.getErrorCode()); sqle.getErrorCode()); sqle.printStrackTrace(System.out); sqle.printStrackTrace(System.out); sqle = sqle.getNextException(); sqle = sqle.getNextException(); }}

Using the JDBC MetaData Interface ResultSet: ResultSetMetaData m = rs.getMetaData() ResultSet: ResultSetMetaData m = rs.getMetaData() ResultSetMetaData provides information about the types and properties of the DDL properties of a ResultSet object ResultSetMetaData provides information about the types and properties of the DDL properties of a ResultSet object ResultSetMetaData provides various methods for finding out information about the structure of a ResultSet: ResultSetMetaData provides various methods for finding out information about the structure of a ResultSet: getColumnClassName(int col): gets fully-qualified Java class name to which a column value will be mapped; eg. Java.lang.Integer, etc.getColumnClassName(int col): gets fully-qualified Java class name to which a column value will be mapped; eg. Java.lang.Integer, etc. getColumnCount(): gets the number of columns in the ResultSetgetColumnCount(): gets the number of columns in the ResultSet getColumnName(int col): gets the name of columngetColumnName(int col): gets the name of column int getColumnType(int col): gets the JDBC type (java.sql.Types) for the value stored in col; eg. Value 12 = JDBC VARCHAR, etc.int getColumnType(int col): gets the JDBC type (java.sql.Types) for the value stored in col; eg. Value 12 = JDBC VARCHAR, etc. getPrecision(int col): for numbers, gets the mantissa length, for others, gets the number of bytes for columngetPrecision(int col): for numbers, gets the mantissa length, for others, gets the number of bytes for column