Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.

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.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
Distributed Application Development B. Ramamurthy.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
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 Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
Objectives Describe JDBC Describe JDBC Driver Types
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. –
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.
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.
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.
Database Programming in Java Corresponds with Chapter 32, 33.
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.
Designing and Developing WS B. Ramamurthy. Plans We will examine the resources available for development of JAX-WS based web services. We need an IDE,
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
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. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
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.
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.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
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.
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)
JDBC Chapter 1 JDBC Introduction
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.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
R EMAINING TOPICS IN JDBC Sagun Dhakhwa. O VERVIEW Introduction to JDBC API Types of JDBC Drivers Introduction to ODBC.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
DEPTT. OF COMP. SC & APPLICATIONS
CS3220 Web and Internet Programming Database Access with JDBC
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
Interacting with Database
JDBC Database Management Database connectivity
Introduction to Programming with Java
Chapter 16 JAVA DATABASE CONNECTIVITY
Design and Implementation of Software for the Web
Objectives In this lesson, you will learn about:
Interacting with Database
JDBC – ODBC DRIVERS.
Java Database Connectivity
Java API for Database Connectivity
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Java Database Connectivity ASE

Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the means for executing SQL statements to access and operate on a relational database l JDBC library is implemented in the java.sql package Set of classes and interfaces that provide a uniform API for access to broad range of databases

Talking to Databases l A JDBC based application is insulated from the characteristics of specific database engines Java Application JDBC Access Database Oracle Database Sybase Database

JDBC Concepts l JDBC’s design is very similar to the design of ODBC l Driver Manager Loads database drivers, and manages the connection between the application and the driver l Driver Translates API calls into operations for a specific data source l Connection A session between an application and a database

JDBC Concepts (contd.) l Statement An SQL Statement to perform a query or update operation l Metadata Information about returned data, the database and the driver l ResultSet Logical set of columns and rows returned by executing an SQL statement (resulting tuples)

Steps during execution l The following steps are executed when running a JDBC application Import the necessary classes Load the JDBC driver Identify the database source Allocate a “connection” object (create) Allocate a “Statement” object (create) Execute a query using the “Statement” object Retrieve data from the returned “ResultSet” object Close the “ResultSet” object Close the “Statement” object Close the “Connection” object

JDBC Component Interaction Driver Manager ConnectionStatementResultSet Driver Database Creates SQL Result (tuples) Establish Link to DB

Steps Involved in Basic JDBC Operations Driver Driver Manager Connection Statement Result Set 1. Load the JDBC driver class: Class.forName(“driverName”); 2. Open a database connection: DriverManager.getConnection (“jdbc:xxx:datasource”); 3. Issue SQL statements: stmt = con.createStatement(); stmt.executeQuery (“Select * from myTable”); 4. Process result set: while (rs.next()) { name = rs.getString(“name”); amount = rs.getInt(“amt”); } Database

Database Access with a JNDI Service Driver Naming Service Connection Statement Result Set 1. Get a DataSource using JNDI InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(“datasourcename”); 2. Open a database connection: Connection con = ds.getConnection(); 3. Issue SQL statements: stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeQuery (“Select * from myTable”); 4. Process result set: while (rs.next()) { name = rs.getString(“name”); amount = rs.getInt(“amt”); } Database

Two-Tier Database Access Model l Java Application talks directly to the database l Accomplished through the JDBC driver which sends commands directly to the database l Results sent back directly to the application Application Space Java Application JDBC Driver Database SQL Command Result Set

Three-Tier Database Access Model l JDBC driver sends commands to a middle tier, which in turn sends commands to database. l Results are sent back to the middle tier, which communicates them back to the application Application Space Java Application JDBC Driver Database SQL Command Result Set Application Server (middle-tier) Proprietary Protocol

JDBC Driver Types l JDBC-ODBC Bridge, plus ODBC driver (Type 1) Simplest JDBC methods -> Translate JDBC methods to ODBC methods -> ODBC to native methods -> Native methods API l Native-API, partly Java driver (Type 2) JDBC methods -> Map JDBC methods to native methods (calls to vendor library) -> Native methods API (vendor library) l JDBC-net, pure Java driver (Type 3) JDBC methods -> Translate to Native API methods through TCP/IP network -> Native API methods l Native-protocol, pure Java driver (Type 4) Java methods -> Native methods in Java

Type 1: JDBC-ODBC Bridge, Plus ODBC Driver l This driver type is provided by Sun with JDK l Provides JDBC access to databases through ODBC drivers l ODBC driver must be configured for the bridge to work l Only solution if no JDBC driver available for the DBMS Application Space Java Application JDBC – ODBC Bridge Database SQL Command Result Set ODBC Driver Proprietary Protocol

Type 2: Native-API, Partly Java Driver l Native-API driver converts JDBC commands into DBMS- specific native calls l Same restrictions as Type1 – must have some binary code loaded on its machine l Directly interfaces with the database Application Space Java Application Type 2 JDBC Driver Database SQL Command Result Set Native Database Library Proprietary Protocol

Type 3: JDBC-Net, Pure Java Driver l Translates JDBC calls into a database-independent network protocol and sent to a middleware server. l This server translates this DBMS-independent protocol into a DBMS-specific protocol and sent to the database l Results sent back to the middleware and routed to the client Application Space Java Application Type 3 JDBC Driver Database SQL Command Result Set Middleware Space Proprietary Protocol JDBC Driver

Type 4: Native- Protocol, Pure Java Driver l Pure Java drivers that communicate directly with the vendor’s database l JDBC commands converted to database engine’s native protocol directly l Advantage: no additional translation or middleware layer l Improves performance Application Space Java Application Type 4 JDBC Driver Database SQL Command Using Proprietary Protocol Result Set Using Proprietary Protocol

The Four JDBC Driver-Type Architectures

Driver Manager l The DriverManager class is responsible for establishing connections to the data sources, accessed through the JDBC drivers l JDBC database drivers are defined by classes that implement the “Driver” interface l The “Properties” class defined in java.util package defines/stores the property (key) and the corresponding value (object) l You can use the “setProperty” method to set the value of any of the properties E.g: System.setProperty(“jdbc.drivers”, “sun.jdbc.odbc.JdbcOdbcDriver”) The first is the key (or name) for the property to be set and the second argument is the value to be set

Driver Manager (contd) l If a security manager is in effect, may not be able to set the System property – then setProperty() will throw an exception of type “Security Exception” l If not able to set System property, the driver can be loaded explicitly by calling the static method “forName” in the “Class” class and pass the driver argument Eg: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); l The “forName()” method can throw a “ClassNotFoundException” if the driver class is not found. Hence, this function call should be in a try-catch block l The above statement loads the JDBC driver and takes care of any initialization that needs to be done

Connection Object l Creating a connection to a data source l Connection object represents an established connection to a particular data source l A connection object can also be used to query the data source (data and meta data) l Different versions of getConnection() method contained in the DriverManager class that returns a connection object: Connection myconn = DriverManager.getConnection(source); Connection myconn = DriverManager.getConnection(source, username, password); Example String mysource = “jdbc:odbc:technical_library”; Connection myconn = DriverManager.getConnection(mysource); System DSN name – ODBC data source

Statement Object l Provides workspace for creating an SQL query, execute it, and retrieve the results that are returned l Statement objects are created by calling the createStatement() method of a valid connection object l Used to execute an SQL query by calling the executeQuery() method of Statement object l The SQL query string is passed as argument to the executeQuery() method l The result of executing the query is returned as on object of type “ResultSet” l JDBC Provides two other kinds of objects to execute SQL statement: PreparedStatement -> extends Statement class CallableStatement -> extends PreparedStatement class Statement mystatement = myconn.createStatement(); ResultSet myresults = mystatement.executeQuery(“select * from authors”);

ResultSet Object l The results of executing an SQL query are returned in the form of an object that implements the ResultSet interface l ResultSet object contains a “cursor” that points to a particular record (called the current record) l When the ResultSet object is created, the cursor points to the position immediately preceeding the first record l Several methods available to navigate the ResultSet by moving the cursor first(), last(), beforeFirst(), afterLast(), next(), previous(), etc. //returns true if the move is successful isFirst() //whether you reached the beginning of the ResultSet isLast() // whether you reached the end of the ResultSet

Accessing Data in a ResultSet l We can retrieve the value of any column for the current row (specified by the cursor) by name or position Using Name: authorNames.getString(“lastname”); Using Position: authorNames.getString(2); Using the column position is a little bit faster l Methods for Retrieving Column Data getString(), getInt(), getShort(), getFloat(), getDouble(), getTime() etc. l We can always use getString() method for numerical values if we are not going to do some computations l Column names are NOT case sensitive l ResultSetMetaData object has metadata information about records, I.e., column names, data types etc. Name of the ResultSet Method that returns the value of String Name of the column or attribute Second column in the row or tuple

Getting MetaData for a ResultSet l The ResultSetMetaData object encapsulates the metadata for a ResultSet object l Use getMetaData() method of ResultSet object to get the metadata l Some of the methods of ResultSetMetaData object: getColumnName() // returns column name getColumnType() // returns column data type getColumnCount() // # of columns in the row getTableName() //returns the name of the table getColumnLabel() //suggested label for a column for use in printouts l The Types class in java.sql package contains the field types used in SQL Eg: CHAR, VARCHAR, DOUBLE, INT, TIME etc. l Once we know the SQL data type, then we can call the appropriate getXXX() function for getting the value of that column

Scrollable Result Sets l In JDBC1.0, result sets could be navigated in only one direction (forward) and starting at only one point (first row) l Since JDBC 2.0, the cursor can be manipulated as if it were a array index l Methods exist for reading both forward and backward, for starting from any row, and for testing the current cursor location.

JDBC 2.0 Navigation Methods for Scrollable Result Sets boolean next ( ) Advances the cursor to the next row. boolean previous ( ) Moves the cursor back one row. boolean first ( ) Moves the cursor to the first row. boolean last ( ) Moves the cursor to the last row. void beforeFirst ( ) Moves the cursor before the first row, usually in anticipation of calling next ( ) void afterLast ( ) Moves the cursor after the last row, usually in anticipation of calling previous ( ) boolean Moves the cursor to the specified absolute (int row) row. Specifying a negative number moves the cursor relative to the end of the result set;

JDBC 2.0 Navigation Methods for Scrollable Result Sets (contd.) boolean Moves the cursor forward or relative (int row) backward the number of rows specified. boolean True if the cursor is before the isBeforeFirst ( ) first row. boolean True if the cursor is after the isAfterLast ( ) last row. boolean isFirst ( ) True if the cursor is positioned on the first row. boolean isLast ( ) True if the cursor is positioned on the last row.

Creating Scrollable Result Sets l Statement object created with parameters to indicate specific capabilities l Connection.createStatement() method can have up to three parameters: resultSetType – type of scrolling to be used resultSetConcurrency – indicates whether the result set can be updated resultSetHoldability – specifies whether to close cursors when a commit is done l Example stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

Constants in Result Sets l Cursor Related Constants TYPE_FORWARD_ONLY JDBC 1.0-style navigation in which the cursor starts at the first row and can only move forward. TYPE_SCROLL_INSENSITIVE All cursor positioning methods are enabled; the result set doesn’t reflect changes made by others in the underlying table. TYPE_SCROLL_SENSITIVE All cursor positioning methods are enabled the result set reflects changes made by others in the underlying table.

Constants in Result Sets (contd.) l Updating Record Sets CONCUR_READ_ONLY The results set won’t be updatable CONCUR_UPDATABLE Rows can be added and deleted, and columns can be updated. l Closing Cursors HOLD_CURSORS_OVER_COMMIT Do not close cursors after a commit is done. CLOSE_COURSORS_AT_COMMIT Close cursors when a commit is done.