1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes.

Slides:



Advertisements
Similar presentations
16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database.
Advertisements

Copyright  Oracle Corporation, All rights reserved. 2 Java and Databases: An Overview.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
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 - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
Distributed Application Development B. Ramamurthy.
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 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.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
Dale Roberts 8/24/ Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
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 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.
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
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 Utility Classes CS 21b. Some Java Utility Classes Vector Hashtable StringTokenizer * import java.util.*;
 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.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
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.
CS 405G: Introduction to Database Systems Database programming.
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
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 Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
JDBC – Java Database Concentricity
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.
Copyright  Oracle Corporation, All rights reserved. 7 Accessing a Database Using SQLJ.
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.
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 CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
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.)
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.
JDBC (Java Database Connectivity)
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.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
Java Access to RDB Relational databases (RDBs) dominate today, due to:
1st Semester, 2017 Sanghyun Park
JDBC 15-Apr-18.
JDBC – Java Database Connectivity
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
JDBC 15-Nov-18.
Interacting with Database
JDBC Example.
Presentation transcript:

1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes

2 References Orfali, Harkey & Evans Client Server Survival Guide (3rd ed) 1999 Ch.11 p Orfali, R. and Harkey, D (1998) Client/Server Programming with JAVA and CORBA (2nd Ed.) Wiley Ch. 23, 25

3 JDBC SQL database access is the most prevalent client/server application model –I.e these are the services we require most JDBC – is the Java object version of Microsoft ODBC –defines Java class wrappers for SQL database access –can access almost any database service –JDBC drivers are available from almost any Java vendor –java.sql.* package is now part of the Java core

4 JDBC –compliance means the drivers support SQL92 –must implement the java.sql.* classes –must be thread safe JDBC Naming Convention "scott", "tiger” subprotocolthis could be a URL JDBC Classes –JDBC Core Interfaces –Java Language extensions –Java Utility Extensions –SQL Metadata Interfaces

5 JDBC Core Classes –locate DBMS drivers - DriverManagerClass locates the driver for DB you specify –establish connections commit, rollback and the DB isolation level –submit SQL statements 2 extensions –Prepared statement - precompile and execute –Callable statement - stored procedures –process result set manipulate the cursor and get back results

6 Java.sql.* Oracle extensions - the Oracle JDBC classes contained in the classes111.zip file - contain a set of classes that invoke the core classes contained in the java.sql.* package the java.sql.* package was not part of the core classes in JDK 1.0

7 JDBC Drivers

8 Typical Steps Import the JDBC Package Set useful static class variables for driver, DBMS URI, credentials, etc. Register appropriate driver with the DriverManager class Set connection Properties (typically credentials) Invoke the Connection Create SQL statement in a String Invoke Statement on connection Execute SQL statement via appropriate method on Statement object (PTO)

9 Typical Steps  execute(...), executeQuery(...) for SEL, receive ResultSet/s  executeUpdate(...) for INS/DEL/UPD or DDLs, receive integer value indicating row count  automatic commit, unless disabled, in which case an explicit COMMIT must be executed to save changes to database Check for Exceptions Process ResultSet  NB: Columns numbered from 1. Close ResultSet and Statement  Unless multiple transactions, then redefine and reuse Cycle for further operations Close Connection

10 Registering & Connecting: The DriverManager Class oracle.jdbc.driver (classes to support database access and updates in Oracle type formats) // Load the Oracle JDBC driver DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); or Class.forName ("oracle.jdbc.driver.OracleDriver"); // Connect to the database Connection conn = DriverManager.getConnection “S ", “student");

11 Sample Code Code for creating a connection using JDBC with Oracle try { // register the driver to connect to oracle DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // db_con is a connection object that lets us connect to the // database with specified URL/userid/password Connection db_con = DriverManager.getConnection "studentid", "password"); System.out.println("Connection Success"); } catch(SQLException f) { // gives error if the above did not succeed. System.out.println("Connection Failed. SQL Exception"); }

12 Code to retrieve data from the Database using the previously created JDBC Connection object try { // statement object stmt created to execute queries using db_con Statement stmt = db_con.createStatement(); // rset is an object that holds the result of the query ResultSet rset = stmt.executeQuery ("SELECT * FROM authors"); // looping through the resultset object till end while (rset.next()){ // getString gets the string data in col 1 of result // and we would have rset.getInt(2) if col 2 was an integer System.out.println (rset.getString(1)); } } catch(SQLException f) { // error handling for above System.out.println("Cannot retrieve data SQL Exception occured"); }

13 Transactions: The Connection Interface Connection Interface –Session between application and database –Specified by location (URI) and credentials Commit/Rollback –conn.commit(); –conn.rollback(); Ignore Isolation Levels Set Autocommit off –after connect but before any statement conn.setAutoCommit (false);

14 Creating a Statement Object: Connection Interface Statement stmt = conn.createStatement (); stmt.execute (“select empno from emp”); –no parameters PreparedStatement pmst = conn.prepareStatement (“insert into emp (EMPNO, EMPNAME) values (?, ?)”); - setting and getting parameters next slide pstmt.execute(); selectText = "SELECT firstname,lastname FROM addresses"; Statement selectStmt = dbConnection.createStatement(); ResultSet result = selectStmt.executeQuery(selectText); insertText = "INSERT INTO addresses VALUES (1,'John','Smith')"; Statement insertStmt = dbConnection.createStatement(); int rowsInserted = insertStmt.executeUpdate(insertText);

15 Setting Parameters & Getting Fields PreparedStatement  statement is pre-compiled and stored in a PreparedStatement object. Can use this to efficiently execute the statement multiple times  allows IN parameters within the query  referenced by number  setXXX () methods used setXXX(); –pstmt.setString (1, "SCOTT"); getXXX(); –System.out.println( rset.getString (1) ); setNULL(); - don’t use nulls

16 ResultSet Interface Provides access to a table of data generated by executing a Statement Table rows are retrieved in sequence via a cursor pointing to the current row of data Some methods:  next ()  getXXX () methods  wasNull ()—detect SQL NULL values  close ()

17 Executing a Query and Returning the ResultSet ResultSet Interface ResultSet rset = stmt.executeQuery ("SELECT ename FROM emp"); executeUpdate –insert, delete, update execute(): while (rset.next()) System.out.println (rset.getString(1)); This is standard JDBC syntax. The next() method returns false when it reaches the end of the result set. The employee names are materialized as JavaStrings.

18 Closing the ResultSet, Statement and Connection You must explicitly close the ResultSet and Statement objects after you finish using them. rset.close(); stmt.close(); You must close your connection to the database once you finish your work. conn.close();

19 ResultSet Interface void dispResultSet (ResultSet rs) throws SQLException { while (rs.next ()) { System.out.print ("" + rs.getInt (1)) String firstName = rs.getString ("FIRST_NAME"); System.out.print (rs.wasNull () ? “[no first name]” : firstName); System.out.print (rs.getString ("LAST_NAME")); System.out.println (rs.getDate (4)); } rs.close (); }

20 SQLException getMessage(): returns the error message associated with the object that threw the exception printStackTrace(): prints this object name and its stacktrace to the specified print stream This example uses both getMessage() and printStackTrace() to return errors. catch(SQLException e); { System.out.println("exception: " + e.getMessage()); e.printStackTrace(); } OR

21 SQL Exception continued catch (SQLException e) { while(e != null) { System.out.println(e.getMessage()); e = e.getNextException(); password = readEntry ("hold it: "); }

22 SQLJ Overview Embedding SQL statements into a host language - Java Opposed to a CLI to access the database - JDBC SQLJ is similar to the ANSI/ISO embedded SQL standards for C, Fortran and other programming languages –proposed to ANSI/ISO as the SQL and Java Standard –(ANSI x ) In Oracle terms Pro*Java Created by IBM, Oracle, Sybase and Tandem because –OO languages have better type checking –no need for writing a dynamic component because JDBC already exists

23 SQLJ Architecture *.SQLJ Oracle SQLJ translator *.JAVA Oracle Customiser Java Byte Code Java Compiler JAVAC Run Oracle sqlj MyFile.sqlj MyOtherFile.sqlj MyJavaFile.java

24 SQLJ Runtime Configuration SQLJ Application SQLJ Runtime Lib Javasoft ODBC based drivers Oracle JDBC/OCI drivers Oracle thin JDBC driver ODBC C Library OCI C Library Java sockets