NJIT 1 JDBC/Oracle tutorial Using Oracle on NJIT Computers by George Blank, Yong Hong Wu, Luv Tulsidas, and Bijal Desai.

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Advertisements

Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
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
19-Jun-15 SQL. SQL is Structured Query Language Some people pronounce SQL as “sequel” Other people insist that only “ess-cue-ell” is the only correct.
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.
CSE470 Software Engineering Fall Database Access through Java.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
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
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© 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.
Database Programming in Java Corresponds with Chapter 32, 33.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
 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.
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.
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.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
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 (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
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.
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.
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.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
EXAMPLE I An application showing JDBC access to Cloudscape.
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.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
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)
Relational Database Management System(RDBMS) Structured Query Language(SQL)
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.
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. Database is used to store data permanently. These days almost all Applications needs database to store its data persistently. Below are the most.
Introduction to Oracle. Before Computerized Database Organization use a set of data files to store each individual data. – The file contains individual.
DEPTT. OF COMP. SC & APPLICATIONS
JDBC 15-Apr-18.
JDBC – Java Database Connectivity
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Interacting with Database
Presentation transcript:

NJIT 1 JDBC/Oracle tutorial Using Oracle on NJIT Computers by George Blank, Yong Hong Wu, Luv Tulsidas, and Bijal Desai

2 Topics covered Resources Setup Oracle environment on NJIT Install Oracle JDBC driver Introduction to Oracle 9 Oracle SQL*Plus Basics Introduction to JDBC JDBC Basics A sample JDBC program Summary References

3 Before Installation You cannot connect to Prophet using JDBC unless you do it from AFS. This is for security. You must use the version of Java installed on AFS and the JDBC drivers in the [ORACLE_HOME]/jdbc directory. You use the Oracle Thin Driver (not the OCI Driver). This is an all Java driver. Every time Oracle or the JDK is upgraded, there may be some changes to this document.

4 Accessing Oracle 10g at NJIT If you have an AFS account and are registered for this class, you should automatically have a Prophet account with Oracle at NJIT. Access prophet using Aqua Data Studio. See information at You should have received your username and password in the already. Use 'course' as Connection Identifier. If you don't have username and password, contact For help, go to and select Databases from the menu on the left.

5 Accessing University Computing Systems You can get to UCS using SSH You can use any system from afs1 to afs36 See for information on SSH and for information on UCS.

6 Testing JDBC Using your Prophet username and password, login to one of the afsnn computers to enter, compile and execute the Java program on the next four slides.

7 Test Program (1) ***************Test.java***************** import java.sql.*; class Test { public static void main (String args []) throws SQLException { // Load the Oracle JDBC driver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

8 Test Program (2) String url = e"; try { String url1 = System.getProperty("JDBC_URL"); if (url1 != null) url = url1; } catch (Exception e) { // If there is any security exception, ignore it // and use the default }

9 Test Program (3) // Connect to the database Connection conn = DriverManager.getConnection (url,"username","password"); // Create a Statement Statement stmt = conn.createStatement (); // Select the SYSDATE column from the dual table ResultSet rset = stmt.executeQuery ("select SYSDATE from dual");

10 Test Program (4) // Print the result while (rset.next ()) System.out.println (rset.getString (1)); // Close the ResultSet rset.close(); // Close the Statement stmt.close(); // Close the connection conn.close(); } }

11 Execute Test Program S ave the file and exit, i.e. if using pico type CTRL X and press yes. Compile the java code by typing the following at the command prompt: javac test.java Once the program is successfully compiled, execute it by typing: java test The program will identify whether or not the connection to Oracle was successful.

12 Errors If the program reports that your connection to oracle was unsuccessful or you receive java exceptions, it may be a problem specific to your AFS account.

13 Introduction to Oracle Oracle is an Object Relational Database Management System(ORDBMS). It offers capabilities of both relational and object- oriented database systems.

14 Tools of Oracle The tools provided by Oracle are so user friendly that a person with minimum skills in the field of computers can access them with ease.The main tools are: -SQL *Plus -PL/SQL -Forms -Reports

15 Introduction to SQL SQL was invented and developed by IBM in early 1970’s. SQL stands for Structured Query Language. Oracle’s database Language is SQL, which is used for storing and retrieving information in Oracle. A table is a primary database object of SQL that is used to store data.

16 Introduction to SQL(Cont’d) In order to communicate with the database, SQL supports the following categories of commands:- Data Definition Language- create, alter,drop commands. Data Manipulation Language- insert, select, delete and update commands. Transaction Control Language- commit, savepoint and rollback commands. Data Control Language- grant and revoke commands.

17 Benefits of SQL Non-procedural language, because more than one record can be accessed rather than one record at a time. It is common language for all relational databases. In other words it is portable and it requires very few modifications so that it can work on other databases. Very simple commands for querying, inserting and modifying data and objects.

18 SQL*Plus SQL*Plus is an Oracle specific program which accepts SQL commands and PL/SQL blocks and executes them. SQL*Plus enables manipulation of SQL commands and PL/SQL blocks. It performs many additional tasks as well.

19 Oracle Basics You must have an existing database instance before you can create an oracle relation (table). If you use NJIT Oracle account, you are already given a database instance when DBA opens the account for you. Note that the following discussion is generic, and not specific to NJIT’s Prophet account.

20 Oracle Internal Datatypes Character datatypes: - char datatype - varchar2 datatype - Long datatype Number datatype Date datatype Raw datatype Long raw datatype LOB datatype

21 Data Definition Language Create tables SQL> CREATE TABLE (,,.... CONSTRAINT pk_name PRIMARY KEY (column_name); CONSTRAINT fk_name FOREIGN KEY (column_name)); REFERENCE name1(name2) ON DELETE CASCADE); Alter the existing table SQL> ALTER TABLE MODIFY/ADD (column definition);

22 Data Definition Language(Cont’d) When there is no further use of records in a table and the structure has to be retained, then the records alone can be deleted. SQL>TRUNCATE table ; Drop a table SQL>DROP ;

23 Data manipulation Language Insert a tuple into a table SQL>INSERT VALUES ( value_1, value_2, value_3..); Request for information stored in a table SQL> SELECT column_names FROM table_name; Change the existing records in the table SQL>UPDATE SET =value,….. WHERE condition; Delete the rows in the table SQL>DELETE FROM WHERE condition;

24 Transaction Control Language Transaction Changes can be made permanent to a database only by committing. Commit command is used to end a transaction and make the changes permanent. SQL>COMMIT; Savepoints are like markers to divide a very lengthy transaction to smaller ones. SQL> SAVEPOINT savepoint_id;

25 Transaction Control Language(Cont’d) Rollback command is used to undo the work done in the current transaction. SQL> ROLLBACK ; SQL> ROLLBACK TO SAVEPOINT savepoint_id;

26 Data Control language Grant privilege command: Object privileges can be granted to others using the SQL command GRANT SQL>GRANT privileges on to ; To withdraw the privilege that has been granted to a user, we use REVOKE command. SQL>REVOKE privileges on from ;

27 Introduction to JDBC What is JDBC ? JDBC is a Java API for executing SQL statements. It consists of a set of classes and interfaces written in Java programming language. JDBC provides a standard API for tool/database developers and makes it possible to write database applications using pure Java API.

28 What Does JDBC Do ? JDBC makes it possible to do three things: Establish a connection with a database Send SQL statements Process the results.

29 JDBC Driver Types The JDBC Drivers that we are aware of at this time fit into one of four categories: 1) JDBC-ODBC bridge plus ODBC driver 2)Native-API partly_Java driver 3)JDBC-Net pure Java driver 4)Native-protocol pure Java driver Categories 3 and 4 are the preferred way to access databases from JDBC.

30 JDBC Basics First you need to establish a connection with Oracle database. This involves two steps: (1) load the driver (2) make the connection. To load the driver: for NJIT Oracle account: DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

31 JDBC Basics (cont’d)  Make a connection to have the appropriate driver connect to Oracle by calling Connection Con = DriverManager.getConnection(url,“userID”, “password”); This method returns an open connection you can use to create JDBC statements that pass your SQL statements to the Oracle. For NJIT Oracle account String url

32 JDBC Basics (cont’d) The second step is to create a Statement object to send SQL statement to Oracle. It takes an instance of an active connection to create a Statement object. A Statement has two methods, executeUpdate() and excuteQuery(). Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query_name); stmt.executeUpdate(DDL_statement); ExcuteQuery() executes a prepared SQL statement and returns the result set in a ResultSet object.

33 JDBC Basics (cont’d) ExecuteUpdate() is used for updates and DLL statements only. Nothing should be returned for executeUpdate() method. A SQL exception will be thrown if executeUpdate() returns anything, or executeQuery() returns nothing. The third step is to create an instance of ResultSet to hold query results, as show below. ResultSet rs = stmt.executeQuery(query_name); ResultSet has several useful methods:

34 JDBC Basics (cont’d) next() method works like a pointer moving from the beginning of the result set towards the end. Each time it is invoked, the next row becomes the current row getXXX() method, where XXX is data type, retrieves the value in each column of the result set. The following code accessed the values in the current row of ResultSet rs and prints out the coffee name and price. String query = "select COF_NAME, PRICE from COFFEES"; ResultSet rs = stmt.executeQuery(query);

35 JDBC Basics (cont’d) while (rs.next()) { String s = rs.getString(”Coffee Name"); Float f = rs.getFloat("Price"); System.out.println(s + " " + f); } Using Prepared Statements Prepared Statement object contains a precomplied SQL statement, and it cost less excution time than Statement object. String query = “Update Customer set Phone = ? Where CID = ?”;

36 JDBC Basics (cont’d) PreparedStatement updatePhone = con.prepareStatement(query); UpdatePhone.setString(1, ‘ ’); UpdatePhone.setInt(2, 4567); UpdatePhone.excuteUpdate(); The above code will change the phone number for the customer whose ID is ‘4567’. SetXXX() method takes two arguments, the first one indicates which question mark is to be set, the second one supplies value to it. After the setXXX() method, the SQL statement is equivalent to query = “Update Customer set Phone = ‘ ’ Where CID = 4567”;

37 Summary JDBC makes it very easy to connect to DBMS and to manipulate the data in it. You have to install the oracle driver in order to make the connection. It is crucial to setup PATH and CLASSPATH properly

38 Very Important Make certain you close your connection: con.close(); If you end your program, but do not specifically close the connection, Oracle keeps a connection open. In April of 2002, Oracle had to be shut down and restarted due to hundreds of abandoned opened connections. In the corporate world, creating a problem that caused the database to be shut down would result in disciplinary action. The Database log tells who left the connection open.

39 Problems Encountered What causes the "No suitable driver" error? "No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are specifying is not being recognized by your JDBC driver.

40 Problems Encountered What causes the "No suitable driver" error? (continued) Do not install or upgrade drivers in your AFS account or modify your.profile or.login files in an attempt to get JDBC to work. It is very strictly configured to work with only the particular version of the thin driver and Prophet. Students who tried upgrading the drivers or modifying their profiles have been totally unable to connect.

41 References White,Seth and Maydene Fisher JDBC API Tutorial and Reference, 2nd Ed. Addison- Wesley Graham Hamilton,Rick Cattell, Maydene Fisher. JDBC Database Access With Java, A Tutorial and Annotated Reference Holowczak, Richard. ORACLE SQL*PLUS: An Introduction and tutorial. At Instructions for Prophet can be found at: under Databases on the menuhttp://web.njit.edu/