 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.

Slides:



Advertisements
Similar presentations
16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database.
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.
1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Introduction to XML CS348 Information System Guest Lecture Hazem Elmeleegy.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 32 Java Database.
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
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.
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.
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.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
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.
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.
CS 405G: Introduction to Database Systems Database programming.
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.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
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.
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.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
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.
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)
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.
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.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
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.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC III IS Outline  Scrollable ResultSets  Updatable ResultSets  Prepared statements  Stored procedures.
1st Semester, 2017 Sanghyun Park
JDBC 15-Apr-18.
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
JDBC Example.
Presentation transcript:

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden Calvin College

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(2/25) Overview Introduction An Example Exercise 1 – a simple JDBC connectionExercise 1 JDBC Classes Summary Exercise 2 – recursive SQL with Java/JDBCExercise 2

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(3/25) Database Programming The world of information technology revolves around databases. While interactive interfaces to database systems are useful, most database work is done though database programs. Approaches to database programming:  Embedding commands in a programming language (e.g., SQLJ)  Using a database API (e.g., JDBC, ODBC, ADO.net)  Designing a database programming language (e.g., PL/SQL, T-SQL)

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(4/25) Impedance Mismatch Relational databases fields records tables General-purpose programming languages standard data types classes The problem is to bind: relational fields, records and tables native 4GL variables, arrays and classes

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(5/25) JDBC Sun Microsystem’s database API for Java.  cf. ODBC/ADO.net Supports Sun’s mantra: “Write once, run anywhere”  JDBC supports portability across DBMS vendors.  Java supports portability across hardware platforms. The typical JDBC interaction sequence: 1. Establish a connection to a database 2. Interact with the database 3. Close the connection

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(6/25) A JDBC Example import java.sql.*; class SimpleJDBC { public static void main (String args[]) throws SQLException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection “login", “pswd"); Statement stmt = conn.createStatement(); try { ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next ()) System.out.println (rset.getString(1) + " " + rset.getString(2)); rset.close(); } catch (SQLException se) { System.out.println("oops! can't query the Student table. Error:"); se.printStackTrace(); } stmt.close(); conn.close(); }

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(7/25) The Output % /usr/java/j2sdk1.4.2/bin/javac -classpath /opt/oracle/product/9ir2/jdbc/lib/ojdbc14.jar:. SimpleJDBC.java % /usr/java/j2sdk1.4.2/bin/java -classpath /opt/oracle/product/9ir2/jdbc/lib/ojdbc14.jar:. SimpleJDBC Adam Adams Bert Benson Cathy Cahill Derrick De Vries Ernest Evers Francetta Franks Gabby Gonzales Harold Hornby Inez Inglewood Jack Jansma Kevin Kline Laurance Lancaster Valery Vander Meiden

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(8/25) A JDBC Example import java.sql.*; class SimpleJDBC { public static void main (String args[]) throws SQLException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection “login", “pswd"); Statement stmt = conn.createStatement(); try { ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next ()) System.out.println (rset.getString(1) + " " + rset.getString(2)); rset.close(); } catch (SQLException se) { System.out.println("oops! can't query the Student table. Error:"); se.printStackTrace(); } stmt.close(); conn.close(); } Import the JDBC API definition.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(9/25) A JDBC Example import java.sql.*; class SimpleJDBC { public static void main (String args[]) throws SQLException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection “login", “pswd"); Statement stmt = conn.createStatement(); try { ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next ()) System.out.println (rset.getString(1) + " " + rset.getString(2)); rset.close(); } catch (SQLException se) { System.out.println("oops! can't query the Student table. Error:"); se.printStackTrace(); } stmt.close(); conn.close(); } Create a “standard” Java application.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(10/25) A JDBC Example import java.sql.*; class SimpleJDBC { public static void main (String args[]) throws SQLException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection “login", “pswd"); Statement stmt = conn.createStatement(); try { ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next ()) System.out.println (rset.getString(1) + " " + rset.getString(2)); rset.close(); } catch (SQLException se) { System.out.println("oops! can't query the Student table. Error:"); se.printStackTrace(); } stmt.close(); conn.close(); } Load the JDBC driver for your DBMS and establish a connection to that DBMS.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(11/25) A JDBC Example import java.sql.*; class SimpleJDBC { public static void main (String args[]) throws SQLException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection “login", “pswd"); Statement stmt = conn.createStatement(); try { ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next ()) System.out.println (rset.getString(1) + " " + rset.getString(2)); rset.close(); } catch (SQLException se) { System.out.println("oops! can't query the Student table. Error:"); se.printStackTrace(); } stmt.close(); conn.close(); } Create an SQL statement and pass it to the DBMS. Handle any error that might occur.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(12/25) A JDBC Example import java.sql.*; class SimpleJDBC { public static void main (String args[]) throws SQLException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection “login", “pswd"); Statement stmt = conn.createStatement (); try { ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next ()) System.out.println (rset.getString(1) + " " + rset.getString(2)); rset.close(); } catch (SQLException se) { System.out.println("oops! can't query the Student table. Error:"); se.printStackTrace(); } stmt.close(); conn.close(); } Process the results of the SQL query.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(13/25) A JDBC Example import java.sql.*; class SimpleJDBC { public static void main (String args[]) throws SQLException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection “login", “pswd"); Statement stmt = conn.createStatement(); try { ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next ()) System.out.println (rset.getString(1) + " " + rset.getString(2)); rset.close(); } catch (SQLException se) { System.out.println("oops! can't query the Student table. Error:"); se.printStackTrace(); } stmt.close(); conn.close(); } Close the record set, the statement, and the connection.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(14/25) Exercise 1 Create a simple application with Java and JDBC to print out the contents of a relational table.  The stub code in exercise1 assumes the existence of a MS Access database called lab10.mdb.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(15/25) JDBC Connections Connection conn = “login", “pswd"); The URL string for the connection contains:  the protocol (jdbc)  the vendor (oracle)  the driver (oci8, oci7, thin)  the server (mydb) The Connection class is an interface, so you cannot create Connection objects directly. All interactions between the java program and the database will be done through this object.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(16/25) JDBC Statements There are three classes for sending SQL statements:  Statement – for SQL statements without parameters  PreparedStatement – for precompiled/parameterized statements  CallableStatement – for executing stored procedures These “statements” are Java classes, not individual SQL statements. They can be reused. JDBC Statements are executed with:  executeUpdate() – executes SQL data definition statements  executeQuery() – returns the results of the SQL query JDBC Statements support dynamic SQL statements.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(17/25) JDBC Updates The executeUpdate() statement performs updates: Statement stmt = conn.createStatement(); stmt.executeUpdate("CREATE TABLE Part (" + " id INTEGER PRIMARY KEY, " + " name VARCHAR2(10), " + " cost REAL )"); stmt.executeUpdate("INSERT INTO Part VALUES (1, 'simple', 10)"); When used for DDL statements, executeUpdate() returns 0. When used to modify data, it returns the number of rows affected by the update.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(18/25) JDBC ResultSets The executeQuery() command returns a ResultSet. ResultSet rset = stmt.executeQuery ("SELECT firstName, lastName FROM Student"); while (rset.next()) System.out.println(rset.getString(1) + " " + rset.getString(2)); The ResultSet provides:  a cursor pointing just before the first result row  next(), to get the next row, returning true if successful  getXXX() to retrieve column values of Java type XXX The argument to getXXX() may either be an index number, getInt(1), or a field name, getDouble(“cost”). ResultSet cursors can be:  Forward-only or scrollable  Read-only or read-write

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(19/25) JDBC PreparedStatements Sometimes it is more convenient or efficient to work with precompiled statements. PreparedStatement pstmt = conn.prepareStatement( “SELECT FROM Student WHERE lastName LIKE ?"); The statement can then be configured and run. pstmt.setString(1, ‘Vander%’); ResultSet rset = pstmt.executeQuery() ; The PerparedStatement provides:  setXXX() functions to set the statement values for Java type XXX As with getXXX(), setXXX() arguments may be an index number or a field name.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(20/25) JDBC Transactions JDBC Connections can support transactions. try { conn.setAutoCommit(false); stmt.executeUpdate(“CREATE TABLE t (id INTEGER, name VARCHAR2(10))"); stmt.executeUpdate(“INSERT INTO t VALUES (10, ‘some name’)”); conn.commit(); conn.setAutoCommit(true); } catch (SQLException se) { System.out.println(“SQL Exception:“ + se.getMessage()); conn.rollback(); connsetAutoCommit(true); } This code will rollback() for any form of exception thrown by the code in the try block.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(21/25) Summary This lecture covered the basic concepts for accessing databases from 4 th generation programming languages. It illustrated the concepts using JDBC:  Connections  Statements  ResultSets It also discussed JDBC support for transactions. References ( )

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(22/25) Exercise 2 Use the remaining time to work through the following JDBC exercise.  SQL is not recursive, so it can’t be used to compute the cost of a part and all its sub-parts (and their sub- parts and so forth).  Java is recursive, so it can be used with JDBC to perform this computation.  Start with the code given in exercise2 and then write:  code to load the appropriate database values into the tables.  a recursive Java function that uses JDBC to compute the total cost for potentially complex part. You’ll find the algorithm in the code.

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(23/25) Exercise 2: The Database The parts database has the following relational table design:  Here, a part has its own cost and can have potentially many sub-parts. The count indicates the number of sub-parts required by the super-part. Part name ID cost m SubPart m count

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(24/25) Part ID name price 1 simple complex sub sub subsub subsub Exercise 2: Sample Data Here we see that part 1 is simple in that it has no sub-parts mentioned in the SubPart table. Part 2 is complex in that it has two sub-parts (3 & 4) one of which (4) has its own sub-parts (5 & 6) SubPart PID CID count

 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(25/25) Exercise 2: Hints You may assume that the database contains no “cycles”, e.g., part 1 is made up of part 2’s, which are each made up of part 1’s. Get the trivial case, i.e., part 1, working first. It has no sub-parts. Print out appropriate error message if the given part doesn’t exist.