JDBC. Introduction-JDBC JDBC is a Sun trademark –Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases from Java.

Slides:



Advertisements
Similar presentations
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Advertisements

Database programming in Java An introduction to Java Database Connectivity (JDBC)
Distributed Application Development B. Ramamurthy.
JDBC CS-328. JDBC Java API for accessing RDBMS Allows use of SQL for RDBMS programming Can be used for: –embedded SQL –execution of stored queries.
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 32 Java Database.
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.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
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.
Accessing Databases with JDBC. Introduction to JDBC JDBC provides a standard library for accessing databases by using the JDBC API. JDBC standardizes.
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
Java Database Connectivity (JDBC). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
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.
CSE470 Software Engineering Fall Database Access through Java.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
Database Programming in Java Corresponds with Chapter 32, 33.
1 Java DataBase Connectivity JDBC java.sql.*. 2 Java DataBase Connectivity Draft release of JDBC spec (3/96) Java API for executing SQL statements (Since.
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.
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.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
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.
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.
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.
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–
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)
JDBC - Java Database Connectivity. JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble.
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.
1 JDBC – Java Database Connectivity CS , Spring 2010.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_Oracle10g_JDBC 1 Application Development (JDBC)
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC.
DEPTT. OF COMP. SC & APPLICATIONS
CS3220 Web and Internet Programming Database Access with JDBC
Interacting with Database
JDBC 15-Apr-18.
JDBC Database Management Database connectivity
CS320 Web and Internet Programming Database Access with JDBC
JDBC 21-Aug-18.
Introduction to Programming with Java
JDBC 15-Nov-18.
Interacting with Database
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

JDBC

Introduction-JDBC JDBC is a Sun trademark –Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases from Java. JDBC is a means of accessing SQL databases from Java –JDBC is also a specification for how third-party vendors should write database drivers to access specific SQL versions

The Structured Query Language (SQL) Composed of two categories: –Data Manipulation Language (DML) (DML) statements are used for managing data within schema objects. e.g. –select –delete –update –Data Definition Language (DDL) (DDL) statements are used to define the database structure or schema e.g. –create database –create table –drop database

Data Manipulation Language SELECT - query the database –select * from customer where id > 1001 INSERT - adds new rows to a table. –Insert into customer values (1009, ‘ABC’) DELTE - removes a specified row –delete UPDATE - modifies an existing row –update customers set amount = 10 where id > 1003

Data Definition Language CREATE DATABASE - allows you to create a database CREATE TABLE - allows you to create a table definition in a database DROP TABLE - removes a table from a database ALTER TABLE - modifies the definition of a table in a database

JDBC Architecture consists of two layers: 1.JDBC API, which provides the application-to-JDBC Manager connection. 2.The JDBC Driver API, which supports the JDBC Manager- to-Driver Connection.

JDBC Architecture  The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.  The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.

Main Components of JDBC DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly. Connection : Interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only. Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed. ResultSet: The ResultSet represents set of rows retrieved due to query execution.

JDBC Class Usage Four primary classes of java.sql Package used to 1.load a driver (java.sql.DriverManager) 2.connect to the DB (java.sql.Connection) 3.create a SQL statement (java.sql.Statement) 4.execute a SQL statement (java.sql.ResultSet)

Driver Manager Object Loads the proper driver into your java object –multiple drivers may be loaded to allow connections to multiple databases Provides a common interface to RDBMSs for JDBC Drivers JAVA Application Driver Manager Driver ‘A’ Driver ‘B’ Connection Statement Result Set Connection Statement

Driver Manager Class Methods getConnection(url,”username”,”password”) getDriver registerDriver deregisterDriver getDrivers setLoginTimeout getLoginTimeout setLogStream getLogStream

Connection Object Establish link between the JAVA application and RDBMS allows application to select proper driver when it needs to uses the database URL to make the connection –jdbc: : –e.g. 1.jdbc:odbc:Mydatabase 2.jdbc:derby://localhost:1527/hello

Connection Class Methods createStatement prepareStatement prepareCall NativeSQL setAutoCommit GetAutoCommit commit rollback close isclosed

Statement Object Wrapper of a string containing a SQL statement allows JDBC to decompose the SQL into a set of steps to present to the database via the driver the connection object forwards the statement object to the database to obtain a results set object

Statement Class Methods executeQuery executeUpdate –insert, update, delete close getResultSet

ResultSet Object A container for the rows and columns (a table) acquired as a result of presenting a statement object to the RDBMs using the “executeQuery” statement method

ResultSet Class Methods next close wasNull getString getBoolean getByte getShort getInt getLong getFloat getDouble getNumeric getBytes getDate getTime getTimeStamp getAsciiStream getUnicodeStream getBinaryStream getMetaData etc...

Basic Steps in writing a Java program using JDBC 1.Load the RDBMS specific JDBC Driver (Incase of JDBC 4.0 this is automatically loaded) 2.Open the connection to database which is then used to send SQL statements and get results back. 3.Create JDBC Statement object. This object contains SQL query 4.Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query. 5.Process the resultset 6.Close the Connection

JDBC: Details of Process 1.Load the driver try { Class.forName(" org.apache.derby.jdbc.ClientDriver "); Class.forName(" com.mysql.jdbc.Driver "); } catch { ClassNotFoundException cnfe) { System.out.println("Error loading driver: " cnfe); } 2.Open the connection to database String host = “localhost"; String dbName = “hello"; int port = 1527; String derbyURL = "jdbc:derby://localhost:1527/hello"; String mysqlURL = "jdbc:mysql://" + host + ":" + port + "/" + dbName;

JDBC: Details of Process, cont. Establish the Connection String username = “nbuser"; String password = “nbuser"; Connection con = DriverManager.getConnection(derbyURL,username,password); Optionally, get information about the db system DatabaseMetaData dbMetaData = connection.getMetaData(); String productName = dbMetaData.getDatabaseProductName(); System.out.println("Database: " + productName); String productVersion = dbMetaData.getDatabaseProductVersion(); System.out.println("Version: " + productVersion);

JDBC: Details of Process, cont. 3. Create JDBC Statement object Statement statement = con.createStatement(); 4. Execute a Query String query = "select * from NBUSER.CONTACTS"; ResultSet resultSet = statement.executeQuery(query); –To modify the database, use executeUpdate, supplying a string that uses UPDATE, INSERT, or DELETE

JDBC: Details of Process, cont. 5. Process the Resultset while(resultSet.next()) { System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3)); } –First column has index 1, not 0 –ResultSet provides various get... methods that take a column index or name and returns the data 6. Close the Connection con.close(); –As opening a connection is expensive, postpone this step if additional database operations are expected

Example 1: Basic JDBC Example import java.sql.*; public class TestDriver { public static void main(String[] Args) { try { Class.forName("com.mysql.jdbc.Driver").newInstance();} catch (Exception E) { System.err.println("Unable to load driver."); E.printStackTrace(); } try { Connection C = DriverManager.getConnection( "jdbc:mysql://almaak.usc.edu:3307/menagerie", "root", "xyz"); //?user=root&password=xyz");

Example 1: Basic JDBC Example, cont. Statement s = C.createStatement(); String sql="select * from tab"; s.execute(sql); ResultSet res=s.getResultSet(); if (res!=null) { while(res.next()){//note MySql start with 1 System.out.println("\n"+res.getString(1) + "\t"+res.getString(2)); } c.close(); } catch (SQLException E) { System.out.println("SQLException: " + E.getMessage()); System.out.println("SQLState: " + E.getSQLState()); System.out.println("VendorError: " + E.getErrorCode()); }

Example 2: A Simple Java JDBC GUI application The following Java Windows-based application example shows a JDBC application with GUI interfaces // QueryTest.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; public class QueryTest extends JFrame implements ActionListener{ private JTextField t1, t2, t3; private JLabel l1, l2, l3; JButton b1; Connection conn;

Example 2 (contd..) public QueryTest() { // Construct a Windows frame super("Query Test"); Container c = getContentPane(); c.setLayout(new FlowLayout()); try{ String userName = "root"; String password = "abc123"; String url = "jdbc:mysql://localhost/test"; Class.forName ("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection (url, userName,password); } catch( ClassNotFoundException x) {System.out.println("Driver Exceptions");} catch( SQLException x) {System.out.println("SQL Exceptions");} // Construct label and text field GUI components // t2 is for input query

Example 2 (Contd..) l1 = new JLabel( "Customer Id: "); c.add (l1); t1 = new JTextField( 15); c.add(t1); l2 = new JLabel( "Name: "); c.add (l2); t2=new JTextField( 15 ); c.add(t2); l3 = new JLabel( "Phone: "); c.add (l3); t3=new JTextField( 15 ); c.add(t3); b1 = new JButton("Execute"); c.add(b1); // Registration of Execute button with the action listener so //that actionPerformed method will be invocated when the button is // pressed

Example 2 (Contd…) b1.addActionListener(this); addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e) {System.exit(0);}}); setSize(300,160); // Enable the frame show(); } public void actionPerformed(ActionEvent e) { // JDBC processing if (e.getSource() == b1) { int numCols; // Search for customer information whose CustomerId is given String query = "select * from customers " + "where name like '" + t2.getText() + "'";

Example 2 (Contd..) // Following JDBC code are almost identical with code of last // example try{ Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); numCols = rs.getMetaData().getColumnCount(); while(rs.next()){ t1.setText(rs.getString(1)); t2.setText(rs.getString(2)); t3.setText(rs.getString(3)); } rs.close(); stmt.close(); conn.close();} catch(SQLException ex){ System.out.println("Exceptions");} } } public static void main(String args[]) { new QueryTest();}}

JDBC Driver Types Type 1 (JDBC-ODBC Bridge) (Bridge) Type 2 (Native-API /partly Java driver ) (Native) Type 3 (Pure Java/ Net-Protocol driver) (Middleware) Type 4 (Pure Java/Native Protocol driver) (Pure)

JDBC Drivers JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC Driver CLI (.lib) Middleware Server

Type 1 JDBC-ODBC Bridge Driver JDBC driver translates JDBC call into ODBC calls and redirects ODBC call to an ODBC driver on the DBMS. In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.

Type 1 JDBC-ODBC Bridge Driver When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.

Type 1 JDBC-ODBC Bridge Driver Adv: 1.Single driver implementation to interact with difference data source 2.Vendor independent driver Disadv: 1.It is recommended only for experimental use. 2.Requires installation/configuration on client machines

Type 1 JDBC-ODBC Bridge Driver

JDBC-ODBC Bridge driver

Type 1 JDBC-ODBC Bridge Driver The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2 Native-API + Java Driver It converts JDBC call into database-specific native call i.e. this driver is specific to a particular database. In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor- specific driver must be installed on each client machine.

Type 2 Native-API + Java Driver If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.

Type 2 Native-API + Java Driver Adv: 1.Helps in accessing the data faster as compared to others Disadv: 1.Requires client-side code to be installed, hence not used for the web. Mostly obsolete now

Type 2 Native-API + Java Driver

Native-API + Java Driver

Type 2 Native-API + Java Driver The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3 JDBC-Middleware Driver Type 3 database requests are passed through the network to middleware server that translates Java code into native API DBMS calls. In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.

Type 3 JDBC-Middleware Driver This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases

Type 3 JDBC-Middleware Driver Adv: 1.Pure java driver and hence auto downloadable 2.This driver is server-based, No client code need to be installed. It is suitable for the web. Disadv: 1.Costlier than others

JDBC-Middleware Pure Java Driver

Type 4 Pure Java Driver The Type 4 uses java networking libraries to communicate directly with the database server. It translates JDBC calls into Database specific network calls In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.

Type 4 Pure Java Driver This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Type 4 Pure Java Driver The Type 4 uses java networking libraries to communicate directly with the database server. It translates JDBC calls into Database specific network calls Adv: 1.Pure java driver, hence auto downloadable 2.No client code need be installed. It is most suitable for the web. 3.Does not require a middleware server Disadv: 1.It uses database specific proprietary protocol and is DBMs vendor dependent

Pure Java Drivers

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

PreparedStatement Suppose that you are going to insert 1000 records into a database. Using Statement object,you need to prepare 1000 different SQL INSERT strings as argument to stmt.executUpdate(sqlStr). Running a thousand SQL INSERT is inefficient.

PreparedStatement JDBC provides a class called PreparedStatement, which allows you to pass parameters to SQL statement and execute the same SQL statement multiple times. A PreparedStatement is a pre-compiled SQL statement that is more efficient than calling the same Statement over and over.

Statement object

PreparedStatement

In PreparedStatement, “?” indicates a place holder for parameter. A set of setxxx() methods can be used to fill in the parameters. For ex:

PreparedStatement Connection conn = DriverManager.getConnection( ); PreparedStatement pstmt = conn.prepareStatement( "insert into books values (?, ?, ?)"); pstmt.setInt(1, 4001); pstmt.setString(2, "Web Programming"); pstmt.setString(3, "Kumar"); int rowAffected = pstmt.executeUpdate(); pstmt.setInt(1, 4002); pstmt.setString(2, "Fishing"); rowAffected = pstmt.executeUpdate(); pstmt.close(); conn.close();