33
Session 30 Basics of JDBC

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

Embed Size (px)

Citation preview

Page 1: 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

Session 30

Basics of JDBC

Page 2: 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 Simplified / Session 30 / 2 of 33

Review A Swing menu consists of a menubar,

menuitems and menus. Trees are used to depict information in a

hierarchical, vertical manner. In Swing, we this is accomplished this with the use of the JTree class.

To display data in a tabular form we can make use of the JTable class in Swing.

JProgressBar class is implemented to display graphical progress of a the task .

Swing components work within the Model View Controller (MVC) model.

Page 3: 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 Simplified / Session 30 / 3 of 33

Review Contd… Characteristics common to all Swing components

are content, visual appearance and behavior. The MVC model contains a set of classes and user

interfaces for various platforms, which help in changing the “look and feel” of the component.

KeyStroke handling, action objects, nested containers, virtual desktops, compound borders, drag and drop, Java 2D, customized dialogs, standard dialog classes and generic undo capabilities are some of the special features of Swing.

Page 4: 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 Simplified / Session 30 / 4 of 33

Objectives Explain the concept of database

connectivity Describe ODBC Discuss what is JDBC Discuss why we need JDBC Describe the java.sql package in brief Discuss types of drivers Explain the anatomy of a JDBC program

Page 5: 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 Simplified / Session 30 / 5 of 33

Database A database contains data that is in an

organized form. Client/Server applications make

extensive use of database programming. Activities may involve opening a

connection, communicating with a database, executing SQL statements and retrieving query results.

Standardized APIs are available that simplify database programming. Examples of these are ODBC and JDBC.

Page 6: 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 Simplified / Session 30 / 6 of 33

ODBC Open DataBase Connectivity (ODBC) is

an Application Programming Interface (API) provided by Microsoft for accessing databases.

It uses Structured Query Language or SQL as its database language.

Provides functions to insert, modify and delete data and obtain information from the database.

Page 7: 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 Simplified / Session 30 / 7 of 33

Task The following tasks are performed

within an application that uses ODBC: Establish a connection with the database. Send the SQL statement to the data source. Define the storage area to store the result

set and also the data type of the result set. Trace errors if any and process them. Get the results. Control the transactions. Terminate the connection.

Page 8: 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 Simplified / Session 30 / 8 of 33

How ODBC connection takes place?

Application could be a GUI program Makes use of ODBC to interact with databases Driver Manager is part of Microsoft ODBC and is used to manage various drivers in the system Driver implements the ODBC functions that are not supported by the DBMS software.

Application

ODBCInterface

DriverManager

Access Driver

Oracle Driver

AccessDatabas

eOracle

Database

Page 9: 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 Simplified / Session 30 / 9 of 33

JDBC JDBC is a Java Database Connectivity API

that is a part of the Java Enterprise API. Defines a set of API objects and methods

to interact with databases. JDBC is a must for all Java applications that

access data stored in external data providers like SQL Server, Oracle or Access.

Page 10: 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 Simplified / Session 30 / 10 of 33

Need for JDBC ODBC uses a C interface that has lot of

drawbacks in areas of security, implementation and so on.

A literal translation of the ODBC C interface into a Java API would not be desirable.

ODBC mixes simple and advanced features together and has complex options even for simple queries.

A Java API like JDBC is needed in order to enable a “pure Java” solution.

JDBC is portable. JDBC is a standard interface for Java

programmers to access relational databases.

Page 11: 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 Simplified / Session 30 / 11 of 33

JDBC - ODBC bridge Database Server

SQL Server

JDBC Driver Types

Database ServerOracleODBC

Driver

ODBC DriverDB-

client

JDBC-ODBC Bridge plus ODBC Driver ODBC is not readily convertible to Java as it is a C interface

to Database Management System (DBMS). Sun provides a bridge driver to access ODBC data sources

from JDBC. This is called the JDBC-ODBC Bridge plus ODBC driver. Major limitations of using JDBC-ODBC bridge is that the

JDBC driver’s capabilities depend on the capabilities of the ODBC driver.

Page 12: 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 Simplified / Session 30 / 12 of 33

JDBC Driver Types Contd…

Database Server

JDBC Driver (Java and

Binary Code)

Vendor Specific ProtocolDB-

client

Native API partly-Java Driver JDBC calls are converted into calls on the client API for

DBMS. This driver uses JavaNativeInterface(JNI) that calls the local

database APIs. The Native APIs partly-Java driver calls the Native

Database Library that accesses the database. This driver like the ODBC driver needs binary code on the

client machine. This driver also requires the native database libraries to be

installed and configured on the client’s machine.

Page 13: 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 Simplified / Session 30 / 13 of 33

JDBC Driver

(Pure Java Driver)

Database Server

SQL ServerDB-client

Networking protocol &

middleware

JDBC Driver Types Contd…

Database Server

JDBC-Net pure Java driver Uses a networking protocol and middleware to

communicate with the server. Server then translates the messages communicated

to DBMS specific function calls. Specific protocol used depends on the vendor. No need for client installation. Allows access to multiple back-end databases.

Page 14: 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 Simplified / Session 30 / 14 of 33

JDBC Driver Types Contd…

Database Server

JDBC Driver (Pure Java

Driver)

Vendor Specifi

c Protoc

olDB-client

Native-protocol pure Java driver 100% Java enabled and does not use CLI libraries. Capable of communicating directly with the database. Converts JDBC calls into network protocols such as

TCP/IP and other proprietary protocols used by DBMS directly.

Since many of these protocols are proprietary, the database vendors themselves will be the primary source of usage.

Page 15: 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 Simplified / Session 30 / 15 of 33

JDBC architecture

Java Program

JDBC Driver

Application Server

Database

SQL command Results

Page 16: 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 Simplified / Session 30 / 16 of 33

JDBC architecture Contd…

Application Layer – developer makes calls to database through SQL and retrieves results.

Driver layer – handles all communication with a specific driver implementation. It is responsible for developing code that acts as an interface to the database and supports the JDBC Application level calls.

Four main Java interfaces that every Driver layer must implement are :

Driver, Connection, Statement and ResultSet

The JDBC API interface comprises of two layers:

Page 17: 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 Simplified / Session 30 / 17 of 33

JDBC architecture Contd…

Application layer

Driver layer

Driver

Statement ResultSet

Connection

Implements Interfaces

Page 18: 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 Simplified / Session 30 / 18 of 33

JDBC components Application – here the JDBC methods are used

to execute SQL statements and get results. Driver Manager – to load specific drivers for

an user application. The following tasks are performed by this

component: Locate the driver for a specific database. Process the initialization calls for JDBC

Driver Data Source – User application interacts with

this to get results.

Page 19: 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 Simplified / Session 30 / 19 of 33

java.sql package Contd… JDBC API defines a set of interfaces and

classes used for communicating with the database.

These are contained in the java.sql package. Classes included in this package are :

Date, DriverManager, DriverPropertyInfo, Time, TimeStamp, Types

Interfaces included are : Callable Statement, Connection, DatabaseMetaData, Driver, PreparedStatement, ResultSet, ResultSetMetaData, Statement

Page 20: 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 Simplified / Session 30 / 20 of 33

java.sql package Contd… The exceptions defined by the java.sql

package are: DataTruncation SQLException (java.sql) SQLWarning (java.sql) BatchUpdateException

Page 21: 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 Simplified / Session 30 / 21 of 33

Creating a JDBC application

Begin

Import the java.sql package

Load and Register the

driver

Create a Connection

object

Create a Statement

object

Execute the statement

Close Connection End

Close Resultset object

Close Statement object

Page 22: 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 Simplified / Session 30 / 22 of 33

Exampleimport java.sql.*;import java.util.*;class Jdbctest{public static void main(String args[]){ try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException ce) { System.out.println(ce); } try {

String url = "jdbc:odbc:test";Connection con =

DriverManager.getConnection(url);Statement s = con.createStatement();ResultSet rs = s.executeQuery("select * from

friends");

while(rs.next()){ System.out.print(rs.getString(1)+"\

t");

System.out.print(rs.getString(2)+"\t"); System.out.print(rs.getInt(3) +

"\t");

System.out.print(rs.getDate(4) + "\t"); System.out.println(" "); } } catch(SQLException ce) { System.out.println(ce); } }}

Output

Page 23: 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 Simplified / Session 30 / 23 of 33

Using SQL The executeQuery() method of statement interface is used to

execute a query. It takes an sql query string as an argument and returns the

ResultSet containing the data. To retrieve the name, phone, email and phone number from

the table colleagues, the query to be written in JDBC is: String str = “SELECT name, email, phone FROM

colleagues”; Statement stmt = con.createStatement(); ResultSet rset = stmt.executeQuery(str); The query statement to find out the number of employees who

joined together on the same day and whose job_id is equal to 5 is:

SELECT count(*) FROM Employee WHERE job_id=5 GROUP BY hire_date

Page 24: 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 Simplified / Session 30 / 24 of 33

Using SQL Contd… SQL statements that update the database do

not return the results as ResultSets. Instead they return an integer representing

the number of rows affected. Assume we need to add a new record. Then sql command in JDBC will be: String str = “INSERT into COFFEE VALUES(‘French_Roast’,00049,8.99,0,0)”;

Statement stmt = con.createStatement(); int rowcount = stmt.executeUpdate(str);

Page 25: 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 Simplified / Session 30 / 25 of 33

Exampleimport java.sql.*;import java.util.*;class Jdbctest3{ public static void main(String args[]) {

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException ce) { System.out.println(ce); } try {

String url = "jdbc:odbc:test"; String str = "INSERT INTO friends(name,address,salary)" +"VALUES('Jessica','Alaska',25690)"; Connection con = DriverManager.getConnection(url);

Statement s = con.createStatement(); int rowcount = s.executeUpdate(str); String str1 ="select name, avg(salary) from friends" +" group by name";

ResultSet rs = s.executeQuery(str1);

while(rs.next()){

System.out.print(rs.getString(1) +"\t" ); System.out.print(rs.getInt(2) +"\t" ); System.out.println(" "); } } catch(SQLException ce) { System.out.println(ce); } }}

Output

Page 26: 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 Simplified / Session 30 / 26 of 33

Using SQL Contd… The LIKE operator is used with SQL

statements to compare two strings SELECT * FROM employee WHERE emp_id

LIKE ‘A%’ Data Definition Language statements are

used to create tables, add columns to the existing tables; delete tables and so on CREATE TABLE Emp(emp_name

VARCHAR(25),emp_no VARCHAR(4),emp_age number);

Page 27: 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 Simplified / Session 30 / 27 of 33

Exampleimport java.sql.*;import java.util.*;class Jdbc2{

public static void main(String args[]) {

Connection con; Statement stmt;

String url; String sql;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }

catch(ClassNotFoundException ce) { System.out.println(ce);

} try { url = "jdbc:odbc:test";

con = DriverManager.getConnection(url); sql = "Delete from friends where rtrim(name) like \'Kim\';";

System.out.println(" "); stmt = con.createStatement( ); stmt.executeUpdate(sql);

Page 28: 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 Simplified / Session 30 / 28 of 33

Example Contd…System.out.println("Record for Kim has been deleted");

con.close(); con = DriverManager.getConnection(url); sql = "Update friends set city=\'Adelaide\' where "+ "rtrim(name) like \'Mike\'; "; System.out.println(" "); stmt = con.createStatement(); stmt.executeUpdate(sql); con.close(); System.out.println("Record for Mike updated"); } catch(SQLException ce) { System.out.println(ce); } }}

Output

Page 29: 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 Simplified / Session 30 / 29 of 33

Types of ResultSets Result sets may be scrollable or non scrollable. The three types of result set which are available

are: TYPE_FORWARD_ONLY: The cursor will move

forward only . TYPE_SCROLL_INSENSITIVE: The cursor can move

forward or backward and also can be moved to a particular row relative to the current position.

TYPE_SCROLL_SENSITIVE: It is same as the previous but with the difference is that if any changes are made to the database then the new values are visible.

Page 30: 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 Simplified / Session 30 / 30 of 33

Exampleimport java.sql.*;import java.util.*;class JdbctestReverse{ public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException ce) { System.out.println(ce); } try { String url = "jdbc:odbc:test"; Connection con = DriverManager.getConnection(url); Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = s.executeQuery("select * from friends"); rs.afterLast();

while(rs.previous()) { System.out.print(rs.getString(1)+"\t"); System.out.print(rs.getString(2)+"\t"); System.out.print(rs.getInt(3) + "\t"); System.out.print(rs.getDate(4) + "\t"); System.out.println(" "); } } catch(SQLException ce) { System.out.println(ce); } }}

Output

Page 31: 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 Simplified / Session 30 / 31 of 33

Summary ODBC is a widely used API provided by

Microsoft to help dealing with databases It uses SQL as its language and provides

functions to insert, modify and delete data. The driver manager is part of Microsoft ODBC

and is used to manage various drivers in the system.

The driver is the actual software component that interacts with the databases and they are software specific such as SQL Server Driver, Ms Access Driver etc.

JDBC is a Java Database Connectivity API that is a part of the Java Enterprise APIs provided by Sun Microsystems.

Page 32: 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 Simplified / Session 30 / 32 of 33

Summary Contd… JDBC defines a set of API objects and methods to

interact with databases The JDBC classes are present in the java.sql

package and all Java programs that need to interact with databases use methods from this package.

We load the driver into the Java interpreter using the Class.forName() method

Then, we establish a connection using the getConnection() method of DriverManager class.

Next we use the createStatement() method of the Connection object .

And finally we construct and execute SQL statements through the statement instance by using either executeQuery() or executeUpdate() methods

Page 33: 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 Simplified / Session 30 / 33 of 33

Summary Contd… It is possible to execute all sorts

of Data Manipulation Language statements of SQL such as Create, Update through the statement instance.

ResultSet can be scrollable or non scrollable.