Lecture 2 Introduction to JDBC. Introducing JDBC 4 According to Sun, JDBC is not an acronym, but is commonly misinterpreted to mean Java DataBase Connectivity.

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.
1 JDBC Java Database Connectivity. 2 c.pdf
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
CS JDBC Introducing JDBC JDBC: is an API that provides “universal data access for the Java2 platform” Allows you to connect to a known data source.
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:
Dale Roberts 8/24/ Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
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
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). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
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.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
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.
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 Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
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.
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
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.
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. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
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.
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.
Lecture 2 Introduction to JDBC. Introducing JDBC  According to Sun, JDBC is not an acronym, but is commonly misinterpreted to mean Java DataBase Connectivity.
Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.
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 CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
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)
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.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
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.
JDBC. Database is used to store data permanently. These days almost all Applications needs database to store its data persistently. Below are the most.
JDBC.
CS JDBC.
DEPTT. OF COMP. SC & APPLICATIONS
JDBC Database Management Database connectivity
Objectives In this lesson, you will learn about:
Interacting with Database
Lecture 2 Introduction to JDBC.
Presentation transcript:

Lecture 2 Introduction to JDBC

Introducing JDBC 4 According to Sun, JDBC is not an acronym, but is commonly misinterpreted to mean Java DataBase Connectivity 4 Supports ANSI SQL 92 Entry Level

The Standard Query Language (SQL) 4 Composed of two categories: –Data Manipulation Language (DML) used to manipulate the data –select –delete –update –Data Definition Language (DDL) create database create table drop database

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

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

JDBC Framework 4 The JDBC driver manager 4 The JDBC driver

The JDBC Driver Manager 4 Management layer of JDBC, interfaces between the client and the driver. 4 Keeps a hash list of available drivers 4 Manages driver login time limits and printing of log and tracing messages 4 Secure because manager will only allow drivers that come from local file system or the same initial class loader requesting a connection 4 Most popular function: –Connection getConnection(url, id, passwd);

JDBC Driver Types 4 Type 1 (JDBC-ODBC Bridge Technology) 4 Type 2 (JNI drivers for C/C++ connection libraries) 4 Type 3 (Socket-level Middleware Translator) 4 Type 4 (Pure Java-DBMS driver)

Type 1 Drivers JDBC-ODBC Bridges 4 JDBC driver translates call into ODBC and redirects ODBC call to an ODBC driver on the DBMS 4 ODBC binary code must exist on every client 4 Translation layer compromises execution speed to small degree

Type 2 Drivers Native-API + Java Driver 4 Java driver makes JNI calls on the client API (usually written in C or C++) –eg: Sybase dblib or ctlib –eg: Oracle Call Interface libs (OCI) 4 Requires client-side code to be installed 4 Often the fastest solution available 4 Native drivers are usually delivered by DBMS vendor 4 bug in driver can crash JVMs 4 Example: JDBC=>Sybase dblib or ctlib

Type 3 Drivers JDBC-Middleware Pure Java Driver 4 JDBC driver translates JDBC calls into a DBMS- independent protocol 4 Then, communicates over a socket with a middleware server that translates Java code into native API DBMS calls 4 No client code need be installed 4 Single driver provides access to multiple DBMSs, eg. WebLogic Tengah drivers 4 Type 3 drivers auto-download for applets.

Type 4 Drivers Pure Java Drivers 4 Java drivers talk directoy to the DBMS using Java sockets 4 No Middleware layer needed, access is direct. 4 Simplest solution available. 4 No client code need be installed. 4 Example: JConnect for Sybase 4 Type 4 drivers auto-download for applets

Result Sets and Cursors 4 Result Sets are returned from queries. 4 Number of rows in a RS can be zero, one, or more 4 Cursors are iterators that iterate through a result set 4 JDBC 2.0 allows for backward as well as forward cursors, including the ability to go to a specific row or a relative row

A JDBC Primer 4 First, load the JDBC Driver: –call new to load the driver’s implementation of Driver class (redundant-- Class.forName does this for you automatically) and call DriverManager.RegisterDriver() –add driver to the jdbc.drivers property - DriverManager will load these automatically eg: ~/.hotjava/properties: –jdbc.drivers=com.oracle.jdbc.OracleDriver:etc; or programatically: –String old = sysProps.getProperty(“jdbc.drivers”); –drivers.append(“:” + oldDrivers); –sysProps.put(“jdbc.drivers”, drivers.toString()); –call Class.forName and pass it the classname for the driver implementation

Create a Connection to the database vi the driver 4 Call the getConnection method on the DriverManager object. 4 Connection conn = DriverManager.getConnection(url, login, password) 4 url: jdbc:subprotocol:host:port[/database] –registered subprotocol: sybase, odbc, msql, etc. –eg: jdbc:sybase:Tds:limousin:4100/myDB 4 Only requirement: The relevant Drivers must be able to recognize their own URL

SQL Statements 4 Create some form of Statement –Statement Represents a basic SQL statement Statement stmt = conn.createStatement(); –PreparedStatement A precompiled SQL statement, which can offer improved performance, especially for large/complex SQL statements –Callable Statement Allows JDBC programs access to stored procedures

Execute the Statement 4 executeQuery(): execute a query and get a ResultSet back 4 executeUpdate(): execute an update and get back an int specifying number of rows acted on –UPDATE –DELETE 4 execute(): execute unknown SQL and returns true if a resultSet is available: –Statement genericStmt = conn.createStatement(); –if( genericStmt.execute(SQLString)) { ResultSet rs = genericStmt.getResultSet(); process(); } –else { int updated = genericStmt.getUpdateCount(); processCount(); –} etc.

Result Sets 4 ResultSet rs = stmt.executeQuery(“select id, price from inventory”); –rs.next() - go to next row in ResultSet call once to access first row: while(rs.next()) {} –getXXX(columnName/indexVal) getFloat() getInt() getDouble() getString() (highly versatile, inclusive of others; automatic conversion to String for most types) getObject() (returns a generic Java Object) –rs.wasNull() - returns true if last get was Null

Prepared Statements 4 Use for complex queries or repeated queries 4 Features: –precompiled at database (statement usually sent to database immediately on creation for compilation) –supply with new variables each time you call it (repeatedly eg.) 4 eg: –PreparedStatement ps = conn.prepareStatement(“update table set sales = ? Where custName = ?”); 4 Set with values (use setXXX() methods on PreparedStatement: –ps.setInt(1, ); –ps.setString(2, “United Airlines”); 4 Then execute: –int count = ps.executeUpdate();

Using the JDBC MetaData Interface 4 ResultSet: ResultSetMetaData getMetaData() 4 ResultSetMetaData provides information about the types and properties of the DDL properties of a ResultSet object 4 ResultSetMetaData provides various methods for finding out information about the structure of a ResultSet: –getColumnClassName(int col): gets fully-qualified Java class name to which a column value will be mapped; eg. Java.lang.Integer, etc. –getColumnCount(): gets the number of columns in the ResultSet –getColumnDisplaySize(int col): gets the normal maximum width in characters for column –getColumnName(int col): gets the name of column –int getColumnType(int col): gets the JDBC type (java.sql.Types) for the value stored in col; eg. Value 12 = JDBC VARCHAR, etc. –getPrecision(int col): for numbers, gets the mantissa length, for others, gets the number of bytes for column

JDBC Transactions 4 A Transaction’s ACID properties are: –Atomic: The entire set of actions must succeed or the set fails –Consistent: consistent state transfer from one state to the next –Isolated: A transaction is encapsulated and unmodifiable until the execution of the transaction set is complete –Durable: Changes committed through a transaction survive and tolerate system failures. 4 Classic Example 1: Bank Transfer from one account to another –Step 1: withdrawal from Account A –Step 2: deposit into Account B

Using Transactions 4 Step 1: turn off autocommit: –conn.setAutoCommit(false); 4 Step 2: create and execute statements like normal 4 Step 3: fish or cut bait: commit or rollback –if all succeeded: conn.commit(); –else, if one or more failed: conn.rollback(); 4 Step 4 (Optional): turn autocommit back on: –conn.setAutoCommit(true);

Rolling Back Transactions 4 When you get a SQLException, you are not told what part of the transaction succeeded and what part failed (this should be irrelevant) 4 Best Practice: –try to rollback() (may throw new SQLException) –start over 4 Example: –catch( SQLException e) { try { –conn.rollback(); } catch (SQLException e) { checkPlease(); } –}

Transactions and Performance Implications 4 Favor Transactions: –Disabling auto-commit means fewer commits over the wire (from driver to DBMS) which may cut down on IO overhead at the dataserver 4 Favor Autocommit: –enabling autocommit may improve performance when multiple users are vying for database resources because locks are held for shorter periods of time locks are only held per transaction. In autocommit mode, each statement is essentially a transaction locks may be either page-level or row-level locks, the latter being more efficient (Oracle)

Transaction Isolation Modes 4 TRANSACTION_NONE –Transactions are disabled or unsupported 4 TRANSACTION_READ_UNCOMMITTED –Open policy that allows others to read uncommitted segments of a transaction, high potential for dirty reads 4 TRANSACTION_READ_COMMITTED –Closed policy that disallows others’ reading uncommitted segments. They must block until a commit is received, dirty reads are forbidden. 4 TRANSACTION_REPEATABLE_READ –subsequent read transactions always get same set regardless of alteration until they call commit(), after which they get the changed data 4 TRANSACTION_SERIALIZABLE –as above but also adds row insertion protection as well. If a transaction reads, and another transaction adds a row, and the first transaction reads again, it will get the original set without seeing the new row. 4 Conn.setTransactionIsolation(TRANSACTION_READ_COMMITTED)

Stored Procedures 4 A Stored Procedure is written in a metalanguage defined by the DBMS vendor 4 Used to batch or group multiple SQL statements that are stored in executable form at the database 4 Written in some internal programming language of the DBMS: –Oracle’s PL/SQL –Sybase’s Transact-SQL 4 THESE LANGUAGES ARE NON-PORTABLE from one DBMS to another (with the exception of the SQLJ standard, which allows you to write SQL in standard Java and have that understood by any DBMS that supports the SQLJ standard).

Incompatibilities 4 Oracle Example: –CREATE PROCEDURE IN FLOAT, AS SELECT account_id WHERE balance 4 Sybase Example: –create proc sp_select_min_bal real) as select account_id where balance return

Why Use Stored Procedures? 4 Faster Execution of SQL (compiled and in-memory stored query plan) 4 Reduced Network Traffic 4 Modular Programming 4 Automation of complex or sensitive transactions 4 Syntax checking at time of creation of SP 4 Syntax supports if, else, while loops, goto, local variables, etc., all of which dynamic SQL doesn’t have

Using Stored Procedures 4 Create a CallableStatement (using prepareCall which is similar to prepareStatement) –CallableStatement stmt = conn.prepareCall(“{call sp_setBalance(?,?)}” stmt.registerOutParameter(2, Types.FLOAT); stmt.setInt(1, custID); stmt.setFloat(2, ); stmt.execute(); Float newBalance = stmt.getFloat(2); –Always register OUT or INOUT parameters in stored procedures using registerOutParameter()