JDBC and SQLJ CIS 612 Spring 2009. JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.

Slides:



Advertisements
Similar presentations
Database programming in Java An introduction to Java Database Connectivity (JDBC)
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.
1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 32 Java Database.
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.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Database Connectivity ODBC, JDBC and SQLJ CS2312.
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
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.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
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.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
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.
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.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
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  Oracle Corporation, All rights reserved. 7 Accessing a Database Using SQLJ.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
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.
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.
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
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.
JDBC™ Advanced Concepts
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
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.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
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.
Interacting with Database
JDBC 15-Apr-18.
JDBC Database Management Database connectivity
JDBC 21-Aug-18.
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Interacting with Database
Java API for Database Connectivity
JDBC Example.
Presentation transcript:

JDBC and SQLJ CIS 612 Spring 2009

JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across database servers ◦ Portability across hardware architectures JDBC drivers have been implemented for a number of DB servers (Oracle, SQL Server, DB2, Access, etc.)

JDBC Java Database Connectivity (JDBC) has been part of the standard Java standard edition since JDK 1.1 ◦ Current version is JDBC 3.0 (as of J2SE 1.4) ◦ JDBC classes are contained in the Java package java.sql ◦ A JDBC-ODBC bridge is included so that any ODBC data source available in the JVM host environment can be accessed

JDBC Drivers There are 4 types of JDBC drivers ◦ Type 1 JDBC-ODBC Bridge ◦ Type 2 Native API Driver ◦ Type 3 Network Protocol Driver ◦ Type 4 Native Protocol Driver Types 1 and 2, use platform specific code Types 3 and 4 are all-Java

Type 1

Type 2

Type 3

Type 4

JDBC Steps in JDBC applications ◦ Load JDBC classes (java.sql.*) ◦ Load the JDBC drivers  Class.forName(“oracle.jdbc.driver.OracleDriver”) ◦ Connect to the database  Connection conn = DriverManager.getConnection(url,userid,passwd)  ◦ Interact with DB using JDBC ◦ Disconnect from DB

JDBC Example /**********************************************/ /* A Simple JDBC Program (Section 5.2) */ /* Chapter 5; Oracle Programming -- A Primer */ /* by R. Sunderraman */ /**********************************************/ import java.sql.*; import java.io.*; class simple { public static void main (String args []) throws SQLException, IOException { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e { System.out.println ("Could not load the driver"); } String user, pass; user = readEntry("userid : "); pass = readEntry("password: ");

JDBC Example Connection conn = DriverManager.getConnection( "jdbc:oracle:oci8:"+user+"/"+pass); Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("select distinct eno,ename,zip,hdate from employees"); while (rset.next ()) { System.out.println(rset.getInt(1) + " " + rset.getString(2) + " " + rset.getInt(3) + " " + rset.getDate(4)); } stmt.close(); conn.close(); }

JDBC Example //readEntry function -- to read input string static String readEntry(String prompt) { try { StringBuffer buffer = new StringBuffer(); System.out.print(prompt); System.out.flush(); int c = System.in.read(); while(c != '\n' && c != -1){ buffer.append((char)c); c = System.in.read(); } return buffer.toString().trim(); } catch (IOException e) { return ""; }

The Connection Object A Connection represents a session with a particular database ◦ All SQL statements are executed and results returned in the context of a Connection ◦ A Java program can have multiple Connections to one or more DBs ◦ Default behavior is autocommit ◦ Connection object is used to send statements to the DB server

JDBC SQL Statement Classes There are three classes for sending SQL to the DB server ◦ Statement. Used for SQL statements with no parameters. ◦ PreparedStatement. Used when the same statement, possibly with different parameters is to be called multiple times. ◦ CallableStatement. Used for calling stored procedures.

Other Connection Class Methods public abstract void close() throws SQLException ◦ Immediately release the Connection’s database and JDBC resources public abstract void setAutoCommit (boolean autoCommit) throws SQLException ◦ Pass true to enable autocommit, false to disable it public abstract void rollback() throws SQLException ◦ Useful when autocommit is false public abstract DatabaseMetaData getMetaData() throws SQLException ◦ Get metadata from the DB

PreparedStatement Object PreparedStatement is compiled, can be reused, may contain parameters ◦ Example: PreparedStatement stmt = conn.prepareStatement(“insert into students values (?, ?, ?, ?)” ); … stmt.setString(1, id); stmt.setString(2, fn); stmt.setString(3, ln); stmt.setString(4, mi); stmt.executeUpdate(); /* executeQuery for Select */

ResultSet Class The result of an executeQuery is a single ResultSet object ◦ This class provides access to the table resulting from the query ◦ A cursor points to the current row (initially positioned before the first row. ◦ Use the next method to fetch the next row ◦ The current row’s column values are retrieved using the getXXX methods, where XXX is a Java type.  Pass either an index or the column name to specify which column

ResultSet Class Use the wasNull method to check whether the previously read column value was Null. Use getMetaData to obtain info like number, types and properties of the columns of a ResultSet

Errors and Warnings The SQLException class provides information about errors while accessing the db ◦ Contains the error message as a String object  Retrieve it using the getMessage method ◦ SQLState string identifies the exception according to the X/Open SQL spec  Retrieve it using getSQLState method ◦ Link to the next exception  Retrieve it using getNextException method

Errors and Warnings try { some JDBC statement to access the DB; } catch (SQLException e) { System.out.println(“SQL Exception caught!”); while (e!= null) { System.out.println(“Error Message = “ + e.getMessage()); System.out.println(“SQL State = “ + e.getSQLState()); System.out.println(“Error Code = “ + e.getErrorCode()); e = e.getNextException(); }

Errors and Warnings The SQLWarning class provides info about warnings generated during DB access ◦ Use getMessage to get the warning string ◦ Use getSQLState to get warning according to X/Open SQL Spec ◦ Use getErrorCode for vendor specific code ◦ Use getNextWarning for next warning generated

Scrollable ResultSet Since JDBC 2.0, ResultSet objects are now updatable and scrollable ◦ The Statement object must be created using the following Connection class method ◦ Statement createStatement(int resultSetType,  Int resultSetConcurrency) ◦ Where resultSetType is one of: TYPE_FORWARD_ONLY (default – old behavior), TYPE_SCROLL_INSENSITIVE (can scroll forwards and back, don’t see changes to ResultSet object in the DB), TYPE_SCROLL_SENSITIVE (changes are visible)

Scrollable ResultSet The resultSetConcurrency parameter takes one of the following values: ◦ CONCUR_READ_ONLY (default – old behavior) data is read only ◦ CONCUR_UPDATABLE – the Java program can make changes to the database based on the new methods and positioning of the cursor Create the scrollable ResultSet using the usual executeQuery method of the Statement object

Scrollable ResultSet Methods for cursor positioning include ◦ absolute(int row) ◦ relative(int row) ◦ first() ◦ last() ◦ previous() ◦ next() ◦ beforeFirst() ◦ afterLast()

More on Statements The Statement interface provides three different methods for executing SQL statements ◦ We have already seen executeQuery for statements that produce a result set ◦ The method executeUpdate is used to execute INSERT, UPDATE, DELETE or DDL statements  The return value is an integer indicating the number of rows affected by an update (0 for a DDL statement)

More on Statements The execute method should be used only when it is possible that a statement may return more than one ResultSet object, more than one update count, or a combination of these ◦ Possibly through executing a stored procedure call, or through executing a SQL statement which is unknown at compile time (e.g. use JDBC to implement SQL*Plus) ◦ Returns true if first result is a result set, false if it is an update count

CallableStatement A CallableStatement object provides a way to call stored procedures in a standard way for all vendor DBs ◦ Written using “escape syntax” (syntax the driver must translate for a particular DB) with one of two forms  Without result parameter – {call proc_name[(?,?, …)]}  With result parameter – {? = call proc_name[(?,?, …)]}

CallableStatement Passing IN parameters is done using the setXXX methods inherited from PreparedStatement ◦ pstmt.setLong(1, 12345); pstmt.setLong(2, 345); If OUT parameters are used, the JDBC type of each OUT parameter must be registered before execution ◦ cstmt.registerOutParameter(1, java.sql.Types.TINYINT); ◦ Then use getXXX methods to retrieve OUT parameter values  byte x = cstmt.getByte(1);