JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Slides:



Advertisements
Similar presentations
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.
Advertisements

1 JDBC Java Database Connectivity. 2 c.pdf
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
1 Oracle Database Applications Database Connectivity.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
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.
Java Database Connectivity (JDBC). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
Think Possibility Integrating Web Applications With Databases.
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.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Intro to JDBC To effectively use Java Data Base Connectivity we must understand: 1.Relational Database Management Systems (RDBMS) 2.JDBC Drivers 3.SQL.
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.
Database Programming in Java Corresponds with Chapter 32, 33.
CHAPTER 7 Database: SQL, MySQL. Topics  Introduction  Relational Database Model  Relational Database Overview: Books.mdb Database  SQL (Structured.
CIS 270—Application Development II Chapter 25—Accessing Databases with JDBC.
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.
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.
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.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
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.
JDBC – Java Database Concentricity
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.
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.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
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–
DataBases and SQL INFSY 547 Spring Course Wrap Up April 12: Complete Work on Servlets Review of Team Projects Close of Portfolio Work April 19:
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.
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 Session 14.
JDBC (Java Database Connectivity)
CS122B: Projects in Databases and Web Applications Winter 2016
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
JDBC - Java Database Connectivity. JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
1 JDBC – Java Database Connectivity CS , Spring 2010.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
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.
Interacting with Database
JDBC.
Interacting with Database
Java Database Connectivity
Java API for Database Connectivity
Java Chapter 6 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

JDBC

Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and organizes data Stores and organizes data SQL SQL Relational database Relational database Structured Query Language Structured Query Language

Relational Database Relational database Relational database Table Table Rows, columns Rows, columns Primary key Primary key Unique data Unique data SQL statement SQL statement Query Query

SQL SQL overview SQL overview SQL keywords SQL keywords

SQL: SELECT QUERY Simplest form of a SELECT query Simplest form of a SELECT query SELECT * FROM tableName SELECT * FROM tableName SELECT * FROM authors SELECT * FROM authors Select specific fields from a table Select specific fields from a table SELECT authorID, lastName FROM authors SELECT authorID, lastName FROM authors

SQL: WHERE CLAUSE specify the selection criteria specify the selection criteria SELECT columnName1, columnName2, … FROM tableName WHERE criteria SELECT columnName1, columnName2, … FROM tableName WHERE criteria SELECT title, editionNumber, copyright SELECT title, editionNumber, copyright FROM titles WHERE copyright > 2000 WHERE clause condition operators WHERE clause condition operators, =, =, <>, =, =, <> LIKE LIKE wildcard characters % and _ wildcard characters % and _

SQL: ORDER BY Clause Optional ORDER BY clause Optional ORDER BY clause SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC ORDER BY multiple fields ORDER BY multiple fields ORDER BY column1 sortingOrder, column2 sortingOrder, … ORDER BY column1 sortingOrder, column2 sortingOrder, … Combine the WHERE and ORDER BY clauses Combine the WHERE and ORDER BY clauses

SQL: INSERT Insert a row into a table Insert a row into a table INSERT INTO tableName ( columnName1, …, columnNameN ) INSERT INTO tableName ( columnName1, …, columnNameN ) VALUES ( value1, …, valueN ) VALUES ( value1, …, valueN ) INSERT INTO authors ( firstName, lastName ) INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ ) VALUES ( ‘Sue’, ‘Smith’ )

SQL: UPDATE Modify data in a table Modify data in a table UPDATE tableName UPDATE tableName SET columnName1 = value1, …, columnNameN = valueN SET columnName1 = value1, …, columnNameN = valueN WHERE criteria WHERE criteria UPDATE authors UPDATE authors SET lastName = ‘Jones’ SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’

SQL: DELETE Remove data from a table Remove data from a table DELETE FROM tableName WHERE criteria DELETE FROM tableName WHERE criteria DELETE FROM authors DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’ WHERE lastName = ‘Jones’ AND firstName = ‘Sue’

Layers of a DB Application A database application consists of three layers A database application consists of three layers Database Management System Database Management System Application logic (business rules) Application logic (business rules) Presentation logic (interface) Presentation logic (interface)

Java DB Support JDBC JDBC Java Data Base Connectivity Java Data Base Connectivity A set of interfaces to provide consistent API for accessing databases from different vendors A set of interfaces to provide consistent API for accessing databases from different vendors Vendors must provide the implementation of these interfaces in order to facilitate a java application to access their database Vendors must provide the implementation of these interfaces in order to facilitate a java application to access their database

JDBC Implemented in java.sql package Implemented in java.sql package Provides set of interfaces to allow access to third party databases Provides set of interfaces to allow access to third party databases Platform independent Platform independent Changes underlying db doesn’t cause significant change in the application Changes underlying db doesn’t cause significant change in the application Also allows access to vendor-specific features Also allows access to vendor-specific features

JDBC Driver JDBC Driver: JDBC Driver: set of classes that interface with a specific database engine. set of classes that interface with a specific database engine. JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL. JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL.

JDBC Driver Java Application JDBC Driver Manager JDBC- ODBC Bridge Vendor Specific JDBC Driver Vendor Specific JDBC Driver Database

Database Drivers Type 1 - Bridge Drivers Type 1 - Bridge Drivers Drivers in Java code which connect a Java client to a non-java database service (such as ODBC). Drivers in Java code which connect a Java client to a non-java database service (such as ODBC). Type 2 - Part-Java Drivers (Native) Type 2 - Part-Java Drivers (Native) Wraps (possibly existing) native code libraries with Java code to implement JDBC. Wraps (possibly existing) native code libraries with Java code to implement JDBC. Type 3 - Network All-Java Drivers (Middleware) Type 3 - Network All-Java Drivers (Middleware) All java code which connects to middleware to access a database via a network protocol. This type of driver may be used with applets or servlets. All java code which connects to middleware to access a database via a network protocol. This type of driver may be used with applets or servlets. Type 4 - Direct All-Java Drivers (Pure) Type 4 - Direct All-Java Drivers (Pure) This provides a pure Java JDBC implementation which can be accessed directly and possibly provide services to networking middleware. This provides a pure Java JDBC implementation which can be accessed directly and possibly provide services to networking middleware.

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

JDBC Application Architecture ApplicationJDBCDriver Java code calls JDBC library Java code calls JDBC library JDBC loads a driver JDBC loads a driver Driver talks to a particular database Driver talks to a particular database Can have more than one driver -> more than one database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code Ideal: can change database engines without changing any application code

JDBC Interfaces CallableStatement CallableStatement Connection Connection DatabaseMetaData DatabaseMetaData Driver Driver PreparedStatement PreparedStatement ResultSet ResultSet ResultSetMetaData ResultSetMetaData Statement Statement

JDBC Classes Date Date DriverManager DriverManager DriverPropertyInfo DriverPropertyInfo Time Time Timestamp Timestamp Types Types

JDBC Six step Procedure Six step Procedure Load the JDBC Driver Load the JDBC Driver Establish the Database Connection Establish the Database Connection Create a Statement Object Create a Statement Object Execute a Query Execute a Query Process the Results Process the Results Close the Connection Close the Connection

JDBC CLASS USAGE DriverManager Driver Connection Statement ResultSet

JDBC: Loading the Driver A simple reference to the driver loads it into the JVM A simple reference to the driver loads it into the JVM Class.forName(name_of_the_driver) Class.forName(name_of_the_driver) Driver name is a string representing the complete hierarchy of the driver class i.e. the package and class name Driver name is a string representing the complete hierarchy of the driver class i.e. the package and class name For a JDBC-ODBC Driver For a JDBC-ODBC Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriv er");

Establish the Connection Static method getConnection of Class Driver Manager returns a Connection object. Static method getConnection of Class Driver Manager returns a Connection object. Can throw SQLException Can throw SQLException Connection con = DriverManager.getConnection(url, user, password ) Connection con = DriverManager.getConnection(url, user, password )

Connection URL The only difficulty in establishing a connection is specifying the correct URL. The only difficulty in establishing a connection is specifying the correct URL. General format of connection URL is jdbc:subprotocol:subname. General format of connection URL is jdbc:subprotocol:subname. JDBC indicates that this is a JDBC Connection. JDBC indicates that this is a JDBC Connection. The subprotocol identifies the driver to be used The subprotocol identifies the driver to be used The subname identifies the database name/location. The subname identifies the database name/location.

Connection URL For example, the following code uses a JDBC-ODBC bridge to connect to the local database db: For example, the following code uses a JDBC-ODBC bridge to connect to the local database db: String url = "jdbc:odbc:db"; Connection con = DriverManager.getConnection(url, "cerami", "password");

Create a Statement Object The JDBC Statement object sends SQL statements to the database. The JDBC Statement object sends SQL statements to the database. Statement objects are created from active Connection objects. Statement objects are created from active Connection objects. For example: For example: Statement stat = con.createStatement(); Statement stat = con.createStatement(); SQL calls can then be made on the database through statement object SQL calls can then be made on the database through statement object

Execute a Query executeQuery(String query) executeQuery(String query) Executes a select query on the database and returns the selected data in the form of a ResultSet object Executes a select query on the database and returns the selected data in the form of a ResultSet object The returned ResultSet object may be empty but cannot be null The returned ResultSet object may be empty but cannot be null Throws SQLException Throws SQLException ResultSet rs = stat.executeQuery (“Select * from table”); ResultSet rs = stat.executeQuery (“Select * from table”);

Execute Query executeUpdate(String query) executeUpdate(String query) Executes INSER, UPDATE, DELETE SQL statements Executes INSER, UPDATE, DELETE SQL statements Returns an integer value representing the number of rows affected by this operation Returns an integer value representing the number of rows affected by this operation Throws SQLException Throws SQLException Also supports DDL statements CREATE TABLE, DROP TABLE, ALTER TABLE Also supports DDL statements CREATE TABLE, DROP TABLE, ALTER TABLE int rows = executeUpdate(“delete * from table”); int rows = executeUpdate(“delete * from table”);

Process the Result A ResultSet contains the results of the SQL query A ResultSet contains the results of the SQL query ResultSet Methods ResultSet Methods All methods can throw a SQLException All methods can throw a SQLException Close() Close() Releases the JDBC and database resources Releases the JDBC and database resources A ResultSet object is automatically closed when its associated statement object runs a new query. A ResultSet object is automatically closed when its associated statement object runs a new query. getMetaData() getMetaData() Returns ResultSetMetaData object Returns ResultSetMetaData object This object contains information about the columns in the ResultSet. This object contains information about the columns in the ResultSet.

ResultSet next() next() Attempts to move to the next row of data in the ResultSet Attempts to move to the next row of data in the ResultSet Returns true if successful and Returns true if successful and False otherwise False otherwise First call to the next() method positions the cursor at the first data row First call to the next() method positions the cursor at the first data row

ResultSet findColumn(String) findColumn(String) Maps a ResultSet column name to a ResultSet column index Maps a ResultSet column name to a ResultSet column index Returns an integer value that corresponds to the specified column name Returns an integer value that corresponds to the specified column name

ResultSet getXXX(String), getXXX(int) getXXX(String), getXXX(int) Returns the value from the column specified by column name (String version) or column index (int) as an XXX Java type Returns the value from the column specified by column name (String version) or column index (int) as an XXX Java type First column index is 1 not 0 First column index is 1 not 0 Returns 0 or null, if the value is a SQL NULL Returns 0 or null, if the value is a SQL NULL Can call wasNull(). Can call wasNull(). Legal getXxx types Legal getXxx types doublebyteint Date Stringfloat short long Time Object

Close the Connection To close the database connection To close the database connection stat.close(); stat.close(); con.close() con.close()

Mapping SQL Types To JAVA SQL type Java Type SQL type Java Type CHAR, VARCHAR, LONGVARCHARString CHAR, VARCHAR, LONGVARCHARString NUMERIC, DECIMALjava.math.BigDecimal NUMERIC, DECIMALjava.math.BigDecimal BITboolean BITboolean TINYINTbyte TINYINTbyte SMALLINTshort SMALLINTshort INTEGERint INTEGERint BIGINTlong BIGINTlong REALfloat REALfloat FLOAT, DOUBLEdouble FLOAT, DOUBLEdouble BINARY, VARBINARY, LONGVARBINARYbyte[] BINARY, VARBINARY, LONGVARBINARYbyte[] DATEjava.sql.Date DATEjava.sql.Date TIMEjava.sql.Time TIMEjava.sql.Time TIMESTAMPjava.sql.Timestamp TIMESTAMPjava.sql.Timestamp

Transaction Management Transactions are not explicitly opened and closed Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed if AutoCommit is true, then every statement is automatically committed default case: true default case: true

Transaction Management Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback() you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

JDBC Class Diagram

Stored Procedures Stored procedures Stored procedures Store SQL statements in a database Store SQL statements in a database Invoke SQL statements by programs accessing the database Invoke SQL statements by programs accessing the database Interface CallableStatement Interface CallableStatement Receive arguments Receive arguments Output parameters Output parameters

Meta Data Database/Connection Database/Connection DatabaseMetaData: getMetaData(); DatabaseMetaData: getMetaData(); ResultSet ResultSet ResultSetMetaData: getMetaData() ResultSetMetaData: getMetaData()

Resultset Metadata What's the number of columns in the ResultSet? What's the number of columns in the ResultSet? What's a column's name? What's a column's name? What's a column's SQL type? What's a column's SQL type? What's the column's normal max width in chars? What's the column's normal max width in chars? What's the suggested column title for use in printouts and displays? What's the suggested column title for use in printouts and displays? What's a column's number of decimal digits? What's a column's number of decimal digits? Does a column's case matter? Does a column's case matter? Will a write on the column definitely succeed? Will a write on the column definitely succeed? Can you put a NULL in this column? Can you put a NULL in this column? Is a column definitely not writable? Is a column definitely not writable? Can the column be used in a where clause? Can the column be used in a where clause? Is the column a signed number? Is the column a signed number? Is it possible for a write on the column to succeed? Is it possible for a write on the column to succeed? and so on... and so on...

Database Metadata What tables are available? What tables are available? What's our user name as known to the database? What's our user name as known to the database? Is the database in read-only mode? Is the database in read-only mode?