JDBC (Java Database Connectivity)

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

Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
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.
JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
EE448: Server-Side Development Slide 1 EE448: Server-Side Development Lecturer: David Molloy Time: Tuesdays 3pm-5pm Notes:
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
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 JDBC "Java Database Connectivity". 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql.
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
Advanced OOP MCS-3 OOP BSCS-3 Lecture # 11. DATABASE CONNECTIVITY IN JAVA JDBC Programming JDBC (Java Database Connectivity) is the specification of a.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
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.
Think Possibility Integrating Web Applications With Databases.
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.
© 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.
JDBC and Hibernate Joshua Scotton. Connecting to Relational DBs.
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.
Introduction to JDBC Michelle Lee, Ye Wu & Jeff Offutt SWE 432 Design and Implementation of Software for the Web.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
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 – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
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.
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.
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.
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.
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.
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
JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.
Basics of JDBC.
Basics of JDBC Session 14.
JDBC - Java Database Connectivity. JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
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.
JDBC.
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
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.
CS320 Web and Internet Programming Database Access with JDBC
HW#4 Making Simple BBS Using JDBC
Interacting with Database
Bolat Azamat, Kim Dongmin
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

JDBC (Java Database Connectivity)

Contents Overview JDBC Programming Steps The PreparedStatement Object History of JDBC JDBC Model JDBC Driver Type JDBC Programming Steps Step 1 : Loading a JDBC Driver Step 2 : Connecting to a Database Step 3 : Executing SQL Step 4 : Processing the Results Step 5 : Closing Database Connection The PreparedStatement Object Transaction and JDBC Summary

Overview (1/2) JDBC(Java Database Connectivity) What does JDBC do? JDBC is a standard interface for connecting to relational databases from Java The JDBC Classes and Interfaces are in the java.sql package JDBC is Java API for executing SQL statements Provides a standard API for database developers Possible to write database applications using a pure Java API Easy to send SQL statements to any relational database What does JDBC do? Establish a connection with a database Send SQL statements Process the results JAVA Applet/ Application Database JDBC Driver Database Command JDBC Call

Overview (2/2) Reason for JDBC Database vendors (Microsoft Access, Oracle etc.) provide proprietary (non standard) API for sending SQL to the server and receiving results from it Languages such as C/C++ can make use of these proprietary APIs directly High performance Can make use of non standard features of the database All the database code needs to be rewritten if you change database vendor or product JDBC is a vendor independent API for accessing relational data from different database vendors in a consistent way

History of JDBC (1/2) JDBC 1.0 released 9/1996. Contains basic functionality to connect to database, query database, process results JDBC classes are part of java.sql package Comes with JDK 1.1 JDBC 2.0 released 5/1998 Comes with JDK 1.2 javax.sql contains additional functionality Additional functionality: Scroll in result set or move to specific row Update database tables using Java methods instead of SQL commands Send multiple SQL statements to the database as a batch Use of SQL3 datatypes as column values

History of JDBC (2/2) JDBC 3.0 released 2/2002 Comes with Java 2, J2SE 1.4 Support for: Connection pooling Multiple result sets Prepared statement pooling Save points in transactions

JDBC Model JDBC consists of two parts: JAVA Applet/ Application Java Application Developer JDBC consists of two parts: JDBC API, a purely Java-based API JDBC driver manager Communicates with vendor-specific drivers JDBC API Driver Manager JDBC Developer Driver API Vender Specific JDBC developer Vendor Specific JDBC Driver JDBC-ODBC Bridge Vender Specific ODBC Driver Database Database

JDBC Driver Type JDBC-ODBC bridge plus ODBC driver Native-API partly-Java driver JDBC-Net pure Java driver Native Protocol pure Java API driver

JDBC Programming Steps Connect Register the driver Create a connection to the database Query Create a statement Query the database Process Results Get a result set Assign results to Java variables Close Close the result set Close the statement Close the connection

Skeleton Code Loading a JDBC driver Class.forName(DRIVERNAME); Connection con = DriverManager.getConnection( CONNECTIONURL, DBID, DBPASSWORD); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member); While(rs.next()) { Int x = rs.getInt(“a”); String s = rs.getString(“b”); Float f = rs.getFloat(“c”); } rs.close(); stmt.close(); con.close(); Connecting to a database Executing SQL Processing the result set Closing the connections

Step 1 : Loading a JDBC Driver A JDBC driver is needed to connect to a database Loading a driver requires the class name of the driver. Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver Oracle driver: oracle.jdbc.driver.OracleDriver MySQL: com.mysql.jdbc.Driver Loaing the driver class Class.forName("com.mysql.jdbc.Driver"); It is possible to load several drivers. The class DriverManager manages the loaded driver(s)

Step 2 : Connecting to a Database (1/2) JDBC URL for a database Identifies the database to be connected Consists of three-part: jdbc:<subprotocol>:<subname> Protocol: JDBC is the only protocol in JDBC Sub-protocol: identifies a database driver Subname: indicates the location and name of the database to be accessed. Syntax is driver specific Ex) jdbc:mysql://oopsla.snu.ac.kr/mydb The syntax for the name of the database is a little messy and is unfortunately vendor specific

Step 2 : Connecting to a Database (2/2) The DriverManager allows you to connect to a database using the specified JDBC driver, database location, database name, username and password. It returns a Connection object which can then be used to communicate with the database. Connection connection = DriverManager.getConnection("jdbc:mysql://oopsla.snu.ac.kr/mydb",“userid",“password"); JDBC URL Vendor of database, Location of database server and name of database JDBC URL Vendor of database, Location of database server and name of database Password Username Password Username

Step 3 : Executing SQL (1/2) Statement object Can be obtained from a Connection object Sends SQL to the database to be executed Statement has three methods to execute a SQL statement: executeQuery() for QUERY statements Returns a ResultSet which contains the query results executeUpdate() for INSERT, UPDATE, DELETE, or DDL statements Returns an integer, the number of affected rows from the SQL execute() for either type of statement Statement statement = connection.createStatement();

Step 3 : Executing SQL (2/2) Execute a select statement Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery ("select RENTAL_ID, STATUS from ACME_RENTALS"); Execute a delete statement Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("delete from ACME_RENTAL_ITEMS where rental_id = 1011"); Dynamically Executing an Unknown SQL Statement The following example uses execute() to dynamically execute an unknown statement: public void executeStmt (String statement) throws SQLException { Statement stmt = conn.createStatement(); // Execute the statement boolean result = stmt.execute(statement); if (result) { // statement was a query ResultSet rset = stmt.getResultSet(); // Process the results ... } else { // statement was an update or DDL int updateCount = stmt.getUpdateCount(); // Process the results ... } }

Step 4 : Processing the Results (1/2) JDBC returns the results of a query in a ResultSet object ResultSet object contains all of the rows which satisfied the conditions in an SQL statement A ResultSet object maintains a cursor pointing to its current row of data Use next() to step through the result set row by row next() returns TRUE if there are still remaining records getString(), getInt(), and getXXX() assign each value to a Java variable ResultSet Internal Pointer Record 1 Record 2 Record 3 Record 4 The internal pointer starts one before the first record

Step 4 : Processing the Results (2/2) Example Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”); While (rs.next()){ int id = rs.getInt(“ID”); String name = rs.getString(“name”); float score = rs.getFloat(“score”); System.out.println(“ID=” + id + “ ” + name + “ ” + score);} NOTE You must step the cursor to the first record before read the results This code will not skip the first record ID name score 1 James 90.5 2 Smith 45.7 3 Donald 80.2 Output ID=1 James 90.5 ID=2 Smith 45.7 ID=3 Donald 80.2 Table1

Step 5 : Closing Database Connection It is a good idea to close the Statement and Connection objects when you have finished with them Close the ResultSet object rs.close(); Close the Statement object stmt.close(); Close the connection connection.close();

The PreparedStatement Object A PreparedStatement object holds precompiled SQL statements Use this object for statements you want to execute more than once A PreparedStatement can contain variables (?) that you supply each time you execute the statement // Create the prepared statement PreparedStatement pstmt = con.prepareStatement(“ UPDATE table1 SET status = ? WHERE id =?”) // Supply values for the variables pstmt.setString (1, “out”); pstmt.setInt(2, id); // Execute the statement pstmt.executeUpdate();

Transactions and JDBC (1/2) Transaction: more than one statement that must all succeed (or all fail) together Ex) updating several tables due to customer purchase If one fails, the system must reverse all previous actions Also can’t leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = cancel all actions

Transactions and JDBC (2/2) The connection has a state called AutoCommit mode If AutoCommit is true, then every statement is automatically committed If AutoCommit is false, then every statement is added to an ongoing transaction Default: true con.setAutoCommit(false); try { PreparedStatement pstmt = con.prepareStatement( "update BankAccount set amount = amount + ? where accountId = ?"); pstmt.setInt(1,-100); pstmt.setInt(2, 13); pstmt.executeUpdate(); pstmt.setInt(1, 100); pstmt.setInt(2, 72); con.commit(); catch (SQLException e) { con.rollback(); }

SQL Types/Java Types Mapping SQL Type Java Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.Math.BigDecimal DECIMAL java.Math.BigDecimal BIT boolean TINYINT int SMALLINT int INTEGER int BIGINT long REAL float FLOAT double DOUBLE double BINARY byte[] VARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp

Summary JDBC Standard interface for connecting to relational databases from Java Vendor independent API for accessing relational data JDBC has four driver type JDBC-ODBC bridge plus ODBC driver Native-API partly-Java driver JDBC-Net pure Java driver Native Protocol pure Java API driver JDBC support transaction and PreparedStatement