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.)

Slides:



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

CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
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.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
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.
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.
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.
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. –
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.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
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.
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.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
Web Design & Development 1 Lec Web Design & Development 2 More on JDBC.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
 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.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
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.
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.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
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.
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.
Copyright  Oracle Corporation, All rights reserved. 7 Accessing a Database Using SQLJ.
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.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
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.
Web Programming MySql JDBC Web Programming.
JDBC™ Advanced Concepts
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
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.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Database Access with JDBC
1st Semester, 2017 Sanghyun Park
Lec - 14.
CS320 Web and Internet Programming Database Access with JDBC
JDBC.
JDBC(Java Database Connectivity
Objectives In this lesson, you will learn about:
COP 4610L: Applications in the Enterprise Spring 2005
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

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.) Working with different types of database drivers 4.) Querying the database Creating a Statement object to perform a query ResultSet or create a PreparedStatement Executing a query and return a ResultSet object Differentiating between a Statement and a PreparedStatement Objectives

3 Objectives (continued) (Steps of the JDBC, continued) 5.) Processing a ResultSet 6.) Closing the ResultSet and Statement 7.) Importance of closing the connection Understand a JBDC row set.

4 What is JDBC? JDBC (Java Database Connectivity) A standard Java interface for connecting from Java to relational databases. The JDBC standard was defined by Sun Microsystems, allowing individual providers to implement and extend the standard with their own JDBC drivers

5 Steps in JDBC 1.Import Packages Import statements at the beginning of your program: import java.sql.Connection; import java.sql.SQLException; or import java.sql.*; Import the ff. Oracle packages when you want to access the extended functionality provided by the Oracle drivers. import oracle.jdbc.pool.OracleOCIConnectionPool; or import oracle.jdbc.*;

6 Steps in JDBC 2. Open a Connection to a Database A call to this method creates an object instance of the java.sql.Connection class. The getConnection() method is an overloaded method that takes Three parameters, one each for the URL, username, and password Only one parameter for the database URL. In this case, the URL contains the username and password The ff. lines of code illustrate using the getConnection() method: Connection conn = DriverManager.getConnection(URL, username, passwd); Or Connection conn = DriverManager.getConnetion(URL); where URL, username and password are of String data types.

7 Steps in JDBC Opening a Connection using the Oracle JDBC OCI: When using the OCI driver, the database can be specified using the TNSNAMES entry in the tnsnames.ora.file. For example, to connect to a database on a particular host as user oratest with password oratest that has a TNSNAMES entry of oracle.world, use the following code: Connection conn = ”, “oratest”, “oratest”);

8 Steps in JDBC 3. Querying the Database Querying the database involves the following steps: Creating a Statement Object This is to instantiate objects that run the query against the database to which they are connected. This is done by the createStatement() method of the conn Connection object created above. A call to this method creates an object instance of the Statement class. The ff. line of code illustrates this: Statement sql_stmt = conn.createStatement(); Or Creating a PreparedStatement A PreparedStatement is associated as a channel with a connection and a compiled SQL statement. PreparedStatements are also created with a Connection method. The following snippet shows how to create a parameterized SQL statement with three input parameters: PreparedStatement prepareUpdatePrice = conn.prepareStatement( "UPDATE Sells SET price = ? WHERE bar = ? AND beer = ?");

9 Steps in JDBC Executing the Query and Returning a ResultSet This is done by using the executeQuery() method of the Statement object. A call to this method takes as parameter a SQL SELECT statement and returns a JDBC ResultSet object. The ff. line of code illustrates this using the sql_stmt object created above: ResultSet rset = sql_stmt.executeQuery (“SELECT empno, ename, sal, deptno FROM emp ORDER BY ename”);

10 Steps in JDBC 4. Process the Result Set Once the query has been executed, there are two steps to be carried out: Processing the output resultSet to fetch the rows next() method of the ResultSet object Retrieving the column values of the current row getXXX() methods of the JDBC rset object Here getXXX() corresponds to the getInt(), getString() etc with XXX being replaced by a Java datatype while (rset.next()) System.out.println (rset.getString(“ename”));

11 Steps in JDBC 5. Closing the ResultSet and Statement Once the ResultSet and Statement objects have been used, they must be closed explicitly. This is done by calls to the close() method of the ResultSet and Statement classes. The ff. code illustrates this: rset.close(); sql_stmt.close(); If not closed explicitly, there are two disadvantages : Memory leaks can occur Maximum Open cursors can be exceeded

12 Steps in JDBC 6. Closing the Connection The last step is to close the database connection after importing the packages and loading the JDBC drivers. This is done by a call to the close() method of the Connection class. The ff. line of code does this: conn.close();

13 package com.jds.architecture.service.dbaccess; import java.sql.Connection; import java.sql.SQLException; import javax.sql.ConnectionPoolDataSource; import oracle.jdbc.pool.OracleOCIConnectionPool; public class OracleOCIDBAccess implements DBAccessInterface { private static String JDBC_URL = private static String USER_ID = "hruser"; private static String PASSWORD = "hruser"; OracleOCIConnectionPool cpool = null; /** * constructor DBAccessException */ protected OracleOCIDBAccess() throws DBAccessException { dbConnect(); } Example Import Packages Declaration OCI driver connection pooling functionality, provided by the OracleOCIConnectionPool class, is part of the JDBC client.

14 public void dbConnect() throws DBAccessException { try{ cpool = new OracleOCIConnectionPool(); cpool.setURL(JDBC_URL); cpool.setUser(USER_ID); cpool.setPassword(PASSWORD); } catch (SQLException e) { throw new DBAccessException ("dbaccess.sql.connection.exception",e.getCause(), DBAccessException.ERROR, true); } catch (Exception e) { e.printStackTrace(); throw new DBAccessException ("dbaccess.oracle.connection.exception",e.getCause(),DBAccess Exception.ERROR, true); } Cont… Initialize the Database Connection

15 /** * Returns database connection from oci connection pool Connection - database connection */ public Connection getConnection() throws DBAccessException { Connection conn = null; try{ conn = cpool.getConnection(); } catch(SQLException e) { throw new DBAccessException ("dbaccess.getconnection.sql.exception", e.getCause(), DBAccessException.ERROR, true); } return conn; } Cont… Open a Connection To a Database

16 Row Set A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use than a result set. A Row Set is an object which encapsulates a set of rows. Kinds of RowSet Objects Connected RowSet object uses a driver based on JDBC technology (“JDBC Driver”) to make a connection to a relational database and maintains that connection throughout its life span. Only one of the standard RowSet implementations is a connected RowSet : JdbcRowSet. Being always connected to a database, it is very similar to a ResultSet object and is often used as a wrapper to make an otherwise nonscrollable and read-only ResultSet object scrollable and updatable. You can create a JdbcRowSet object in two ways: By using the reference implementation constructor that takes a ResultSet object By using the reference implementation default constructor Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(select * from COFFEES); JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);

17 Row Set Using the Default Constructor The following line of code creates an empty JdbcRowSet object. JdbcRowSet jdbcRs2 = new JdbcRowSetImpl(); Disconnected RowSet objects make a connection to a data source only to read in data from a ResultSet object or to write data back to the data source. The other four implementations are disconnected RowSet implementations. 1.A CachedRowSet object has all the capabilities of a JdbcRowSet object plus it can also do the following:  Obtain a connection to a data source and execute a query  Read the data from the resulting ResultSet object and populate itself with that data  Manipulate data and make changes to data while it is disconnected  Reconnect to the data source to write changes back to it  Check for conflicts with the data source and resolve those conflicts

18 Row Set You can create a new CachedRowSet object in two different ways: –By using the default constructor CachedRowSet crs = new CacheRowSetImpl(); –By Passing a SyncProvider implementation to the constructor CachedRowSet crs2 = CachedRowSetImpl(“com.fred.providers.HighAvailabili tyProvider”); 2. A WebRowSet object has all the capabilities of a CachedRowSet object plus it can also do the following: Write itself as an XML document Read an XML document that describes a WebRowSet object WebRowSet pricelist = new WebRowSetImpl(); 3. A JoinRowSet object has all the capabilities of a WebRowSet object (and therefore also a CachedRowSet object) plus it can also do the following: Form the equivalent of an SQL JOIN without having to connect to a data source JoinRowSet jrs = new JoinRowSetImpl();

19 Row Set 4. A FilteredRowSet object likewise has all the capabilities of a WebRowSet object (and therefore also a CachedRowSet object) plus it can also do the following: Apply filtering criteria so that only selected data is visible. This is equivalent to executing a query on a RowSet object without having to use a query language or connect to a data source. FilterRowSet frs = new FilteredRowSetImpl(); This object is initialized with the following: The high end of the range within which values must fall The low end of the range within which values must fall The column name or column number of the value that must fall within the range of values set by the high and low boundaries Filter1 range = new Filter(1000, 10999, “STORE_ID”); The next line of code sets range as the filter for frs. frs.setFilter(range);