Вы находитесь на странице: 1из 48

JDBC

Objectives
Discuss Java Database Connectivity (JDBC) Describe the java.sql package in brief Discuss types of JDBC drivers Explain the anatomy of a JDBC program Describe the PreparedStatement interface

Use ResultSet Interface

Database
Database Programming Executing SQL statements

Client / Server Application

Database

Retrieving query results

ODBC
Two APIs for Java applications

JDBC

ODBC 3-1
Application Programming Interface

Insert

Modify

Client / Server GUI Application

ODBC (Open Database Connectivity)

Database
Delete

ODBC 3-2

Access Driver Application ODBC Interface Driver Manager Oracle Driver Others

Access Database Oracle Database Other Database..

ODBC Connection

ODBC 3-3
Establish a connection with the database

Send 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

JDBC
Java Application Programming Interface Java Application

JDBC (Java Database Connectivity)

Communicates Through API objects and methods

Database

JDBC Driver types


JDBC-ODBC Bridge Plus ODBC Driver

Native API partly Java Driver JDBC Driver types JDBC-Net pure Java driver

Native-protocol pure Java driver

JDBC Driver Type 1

Java Application

JDBC API

ODBC Layer

JDBC ODBC Driver

ODBC API

Database

2/25/2014

Type 1 Driver (JDBC-ODBC Bridge driver)


10

Translates all JDBC API calls to ODBC API calls. Relies on an ODBC driver to communicate with the database. Disadvantages ODBC required hence all problems regarding ODBC follow. Slow

2/25/2014

11

JDBC Driver Type 2

Java Application

JDBC API

Vendor API

JDBC Driver

Database

2/25/2014

12

Type 2 (Native API Partly Java Driver) Written partly in Java & partly in native code, that
communicates with the client API of a database. Therefore, should install some platform-specific code in addition to Java library. The driver uses native C lang lib calls for conversion.

2/25/2014

13

JDBC Driver Type 3

Java Client

JDBC API

JDBC Driver Server

Native Driver

Database
JDBC Driver

2/25/2014

14

Type 3 (pure network protocol driver) Uses DB independent protocolJava to communicate DBrequests to a server component. This then translates requests into a DB-specific protocol.

Since client is independent of the actual DB, deployment is simpler & more flexible.

2/25/2014

15

JDBC Driver Type 4


Vendor-Specific Protocol
JDBC API

Java Client

JDBC Driver (Pure Java)

Database

2/25/2014

16

Type 4 Driver (Pure drivers) JDBC calls areJava directly converted to network protocol
used by the DBMS server. Driver converts JDBC API calls to direct network calls using vendor-specific networking protocols by making direct socket connections with the DB. But driver usually comes only from DB-vendor.

2/25/2014

JDBC Architecture 2-1


Java Program

JDBC Driver

SQL Command

Results

Application Server

Database

JDBC Architecture 2-2


Application layer
Driver layer Implements Interfaces Driver Statement ResultSet Connection

JDBC Components
import java.sql.*; import java.util.*; class Jdbctest2 { 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 hiredate,sum(salary) from friends group by hiredate"); while(rs.next()) { System.out.print(rs.getDate(1) +"\t" ); System.out.print(rs.getInt(2) +"\t" ); System.out.println(" "); } } catch(SQLException ce) { System.out.println(ce); } } }

Java Application

JDBC Components

Locate the driver for specific database Driver Manager Process initialization calls for JDBC Driver

Data Source

java.sql package 3-1


Interface Name CallableStatement Description This contains methods that are used for execution of SQL stored procedures.

Connection

This is used to maintain and monitor database sessions. Data access can also be controlled using the transaction locking mechanism. This interface provides database information such as the version number, names of the tables and functions supported. This interface is used to create Connection objects.
This is used to execute pre-compiled SQL statements. This interface provides methods for retrieving data returned by an SQL statement. This interface is used to collect the meta data information associated with the last ResultSet object. It is used to execute SQL statements and retrieve data into the ResultSet.

DatabaseMetaData

Driver
PreparedStatement ResultSet ResultSetMetaData Statement

java.sql package 3-2


Class Name
Date DriverManager DriverPropertyInfo Time TimeStamp Types

Description
This class contains methods for performing conversion of SQL date formats to Java Date formats. This class is used to handle loading and unloading of drivers and establish connection with the database. The methods in this class are used to retrieve or insert driver properties. This class provides formatting and parsing operations for Time values. This provides precision to Java Date object by adding a Nanosecond field. This class has no methods. This class defines the constants used to identify the SQL types.

java.sql package 3-3


Introducing java.sql package. The exceptions defined by the java.sql package are:

try{ DataTruncation Calling fooBar fooBar(); //--- SQLException catch(SQLException ex) //fooBar SQLWarning { //--- BatchUpdateException //If an SQLException is thrown, well end up here. public void foobar() throws SQLException //Output is the error message, SQLstate and vendor { code. throw new SQLException(I just threw an System.out.println(An SQLException was caught!); SQLException); System.out.println(Message: + ex.getMessage()); } System.out.println(SQLState: + ex.getSQLState()); System.out.println(Vendor Code: + ex.getErrorCode()); }

Steps for Database Access


Begin Import the java.sql package Load and register the driver Create a Connection object Create a statement object Execute the statement

Close the Connection

Close Statement object

Close ResultSet object

End

Anatomy of a JDBC program


/** This is a main method. */ public static void main(final String [] args) { It demonstrates the different steps to access a database. try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Before Example 1 can be executed, } catch (ClassNotFoundException ce) { a table named friends System.out.println(ce); import java.sql.SQLException; should exist in SQL Server. } import java.sql.Connection; try { Column Name Data Type import String java.sql.DriverManager; url = "jdbc:odbc:test"; import Connection java.sql.Statement; Name con = DriverManager.getConnection(url); Varchar import Statement java.sql.ResultSet; s = con.createStatement(); Address Varchar ResultSet rs = s.executeQuery("select from friends"); /** This class demonstrates the different* steps followed while (rs.next()) { Numeric to access a database. Telephone System.out.print(rs.getString(1) + "\t"); */ System.out.print(rs.getString(2) + "\t"); HireDate Datetime class Jdbctest { System.out.print(rs.getInt(3) + "\t"); /** Constructor. */ Salary Numeric System.out.print(rs.getDate(4) + "\t"); protected Jdbctest() { System.out.println(" "); }} Friends table structure } catch (SQLException ce) { System.out.println(ce); } }}

Demonstration: Example 1

Creating a new data source 9-1

Double-Click Select Data the Sources Administrative (ODBC) icon Tools

Click on Settings Control Panel Administrative Tools

Creating a new data source 9-2

Click on Add button to open the Create New Data Source window Select the System DSN tab

Creating a new data source 9-3

Choose SQL Server Click on Finish button to open the Create a New Data Source to SQL Server dialog box

Creating a new data source 9-4

Type the data source name and description as test and select a system name on which SQL Server is Click on Next to open the option installed. SQL Server name for example, SQL Server for login authentication

Creating a new data source 9-5

Choose the default settings

Click on Next

Creating a new data source 9-6

allows the user to choose database. For this example it is friends. Click on Finish in next Dialog box. Click on Next. The dialog box displays default settings. Select default settings.

Creating a new data source 9-7

Click on Test Data Source to check for the connection

Creating a new data source 9-8

Click on OK

Creating a new data source 9-9

The data source name appears in the System DSN tab

Using SQL 5-1


Statement interface

SQL Query String

executeQuery() Method

ResultSet

Passed as an argument

Returns selected data

In SQL, query can be written as SELECT name, email, phone FROM colleagues; for JDBC the Java code to execute the above query would be String str = "SELECT emp_id, lname, fname FROM colleagues"; Statement stmt = con.createStatement(); ResultSet rset = stmt.executeQuery(str);

Using SQL 5-2


It demonstrates the main(final use of sum() function in { SQL. public static void String [] args)
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); import java.sql.SQLException; } catch (ClassNotFoundException ce) { import java.sql.Connection; System.out.println(ce); import java.sql.DriverManager; } try { String url = "jdbc:odbc:test"; import java.sql.Statement; Connection con = DriverManager.getConnection(url, sa, import java.sql.ResultSet; playware); /** This class demonstrates the use of sum() function in SQL. Statement s = con.createStatement(); ResultSet rs = s.executeQuery( */ "select hiredate, sum(salary) from friends group by class Jdbctest2 { hiredate"); /** while Constructor. */ { (rs.next()) protected Jdbctest2() { System.out.print(rs.getDate(1) + "\t"); } System.out.print(rs.getInt(2) + "\t"); System.out.println(" "); } } catch (SQLException ce) { System.out.println(ce); } }}
/** This is a main method.*/

Demonstration: Example 2

Using SQL 5-3


/** is a main the method. */ of INSERT statement in SQL. ItThis demonstrates usage public static void main(final String [] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); import java.sql.SQLException; } catch ResultSet rs(ClassNotFoundException = s.executeQuery(str1);ce) { import java.sql.Connection; System.out.println(ce); while (rs.next()) { import java.sql.DriverManager; } System.out.print(rs.getString(1) + "\t"); import tryjava.sql.Statement; { System.out.print(rs.getInt(2) + "\t"); import java.sql.ResultSet; String url = "jdbc:odbc:test"; System.out.println(" "); /** } ThisString class str demonstrates usage of INSERT statement. = "INSERTthe INTO */ friends(name,address,salary)" } catch (SQLException ce) + { class Jdbctest3 { "VALUES('Jessica','Alaska',25690)"; System.out.println(ce); /** } Constructor. */con = DriverManager.getConnection(url); Connection protected Jdbctest3() { Statement s = con.createStatement(); } } int rowcount = s.executeUpdate(str); } String str1 = "select name, avg(salary) from friends" Demonstration: Example 3 + " group by name";

Using SQL 5-4


Statement
ALTER TABLE <tableName>

Syntax
ALTER TABLE emp ADD (emp_email char(20))

Description
A new column called emp_email is added to the table emp of character size 20. The values specified here are inserted into the table emp. Deletes all the rows with the emp_name equal to Bradman from the emp table.

INSERT INTO INSERT INTO emp <tableName> VALUES (Jennifer,E004,32,jenni @abc.com) DELETE FROM <tablename> DELETE FROM emp WHERE emp_name = Bradman

DROP TABLE <tableName>

DROP TABLE emp

The table named emp is permanently removed from the database.

Using SQL 5-5


public static void main(final String [] args) It demonstrates the usage of commands in { SQL. Connection con; Statement stmt; String url; String sql; import try java.sql.SQLException; { con = DriverManager.getConnection(url); import java.sql.Connection; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); sql = "Update friends set address=\'Adelaide\' import java.sql.DriverManager; } catch (ClassNotFoundException ce) { where " + "rtrim(name) like \'Mike\'; "; import java.sql.Statement; System.out.println(ce); System.out.println(" "); /** } This class demonstrates the usage of commands in SQL. stmt = con.createStatement(); */ try { stmt.executeUpdate(sql); class { url Jdbc2 = "jdbc:odbc:test"; con.close(); /** Constructor. */ con = DriverManager.getConnection(url); System.out.println("Record for Mike updated"); protected Jdbc2() { sql = "Delete from friends where rtrim(name)like\'Kim\';"; } catch (SQLException ce) { } System.out.println(" "); System.out.println(ce); stmt = con.createStatement(); } stmt.executeUpdate(sql); Demonstration: Example 4 } System.out.println("Record for Kim is deleted); } con.close();

Prepared Statement interface 3-1


Statement interface

PreparedStatement Interface (Precompiled SQL statements)

PreparedStatement is used to improve runtime efficiency

Executing PreparedStatement objects is faster than Statement objects

PreparedStatement interface 3-2


CourseAppl() { display() { public void It demonstrates the usage of PreparedStatement in SQL. = "jdbc:microsoft:sqlserver://"; try url { con = getConnection(); import serverName java.sql.SQLException; = "10.1.1.234"; PreparedStatement pstmt = con.prepareStatement( import portNumber java.sql.Connection; = "1433"; "UPDATE Course SET=Hours= ? WHERE CourseTitle like ?"); import java.sql.DriverManager; databaseName "Prod"; pstmt.setInt(1, 800); import userName java.sql.Statement; = "john"; pstmt.setString(2, "Windows 2003"); import password java.sql.ResultSet; = "playware"; } pstmt.executeUpdate(); import String java.sql.PreparedStatement; private getConnectionUrl() { System.out.println("Record updated!"); /** This class demonstrates usage of PreparedStatement return url + serverName + ":" the + portNumber + ";databaseName =" Statement s = con.createStatement(); SQL. */ + in databaseName + ";"; } String sql = "SELECT * FROM Course"; ResultSet rs class CourseAppl { = s.executeQuery(sql); private java.sql.Connection getConnection() { while (rs.next()) private Connection con;{ try { System.out.println(" "); private String url; Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); System.out.print(rs.getInt(1) + " "); private String serverName; con = DriverManager.getConnection( System.out.print(rs.getString(2) + " "); private getConnectionUrl(), String portNumber; userName, password); System.out.println(rs.getInt(3)); databaseName; ifprivate (con !=String null) { }} catch (SQLException ce) { private String userName; System.out.println("Connection Successful!"); System.out.println(ce); private String password; }} (Exception { }} catch /** This is a Example main e) method. Demonstration: 5*/ public static sql; void main(final String [] args) { private String e.printStackTrace(); CourseAppl retObj = new CourseAppl(); System.out.println("Error Trace in getConnection() : " + retObj.display(); }} e.getMessage()); } return con; }

PreparedStatement interface 3-3


public void display() { private String getConnectionUrl() { java.sql.SQLException; import It demonstrates how to use PreparedStatement in an SQL try { //constructing the connection string import java.sql.Connection; conurl = getConnection(); query based upon a condition and condition return + serverName + ":" + the portNumber + is given as import java.sql.DriverManager; sql = "select * from Friends where Salary >?"; ";databaseName =" .+ databaseName + ";"; an IN parameter import java.sql.ResultSet; PreparedStatement pstmt = con.prepareStatement( } import java.sql.PreparedStatement; sql, ResultSet.TYPE_SCROLL_SENSITIVE, private java.sql.Connection getConnection() { /** This class demonstrates the usage of PreparedStatement ResultSet.CONCUR_UPDATABLE); in try{ an SQL query based upon a condition.*/ pstmt.setInt(1, 5000); Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver" class RetrieveRecords { ResultSet rs = pstmt.executeQuery(); ); private while Connection con; (rs.next()) { con = DriverManager.getConnection( private String url; System.out.print(rs.getString(1) + "\t"); getConnectionUrl(), userName, password); private System.out.print(rs.getString(2) String serverName, portNumber, databaseName, + "\t"); if (con != null) { userName,password; System.out.print(rs.getInt(3) +Successful!"); "\t"); private System.out.println("Connection String sql; System.out.print(rs.getDate(4) + "\t"); }} catch (Exception e) { RetrieveRecords() { System.out.print(rs.getInt(5) + "\t"); e.printStackTrace(); url = "jdbc:microsoft:sqlserver://"; System.out.println(" "); System.out.println("Error Trace in getConnection() : " serverName = "10.1.1.234"; }} catch (SQLException ce) { + e.getMessage()); portNumber = "1433"; /** This is a main method.*/ }System.out.println(ce);}} Demonstration: Example 6 databaseName = main(final "Prod"; public static void String [] args) { return con; userName = "john"; RetrieveRecords retRec = new RetrieveRecords(); } password = "playware";} retRec.display(); }}

Working with ResultSets 3-1


ResultSet objects are entirely dependent on the Statement and Connection objects. Each time an SQL statement is executed, the resultset is overwritten with new results. The ResultSet object gets automatically closed when the related Statement is closed.

next()

getRow()

get<Type>()

positions the cursor down one row from its current position

Determines the current row number

Returns the data from the ResultSet object

set of functions

Working with ResultSets 3-2


It demonstrates the processing of current Row. Using the next() method, records are processed in a sequential manner. The processing of data in each row must be achieved in the order in which they are returned.
ResultSet rset = stmt.getResultSet();
while(rset.next()) { String dept_name = rset.getString(1); }

Working with ResultSets 3-3


It To retrieve the value of column of emp_id, the getString() demonstrates the processing current Column. method is passed the value 1. Columns can be directly accessed using the get<Type>() method.
Statement stmt == con.createStatement(); Statement stmt con.createStatement(); Stmt.executeQuery("Select emp_id, fname stmt.executeQuery("Select emp_id, fname from from Employee") ; Employee"); ResultSet rset == stmt.getResultSet(); ResultSet rset stmt.getResultSet(); while(rset.next()) while(rset.next()) {{ String ename = rset.getString ("fname"); String employeeid = rset.getString (1); System.out.println ( ename) ; } }

Types of Result Sets 3-1


Result sets

Scrollable Cursor will move forward only

Non scrollable

TYPE_FORWARD_ONLY

Cursor can move in both directions and can also be moved to a particular row relative to current position If changes are made to database then new values are visible

TYPE_SCROLL_INSENSITIVE

TYPE_SCROLL_SENSITIVE

try {

Types of Result Sets 3-2

String url = "jdbc:odbc:test"; java.sql.SQLException; import It demonstrates the = use of various Result Sets. Connection con DriverManager.getConnection(url, import java.sql.Connection; sa, playware); import Statement java.sql.DriverManager; s = con.createStatement( import ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.Statement; import java.sql.ResultSet; ResultSet.CONCUR_READ_ONLY); /** This class demonstrates the use of various ResultSet.*/ ResultSet rs = s.executeQuery("select * from friends"); class rs.afterLast(); JdbctestReverse { /** Constructor. */ while (rs.previous()) { protected JdbctestReverse() { System.out.print(rs.getString(1) + "\t"); } System.out.print(rs.getString(2) + "\t"); /** This is a main method.*/ System.out.print(rs.getInt(3) + "\t"); public System.out.print(rs.getDate(4) static void main(final String [] args) { + "\t"); try { System.out.println(" "); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ce) { } } catch (SQLException ce) { System.out.println(ce); System.out.println(ce); Demonstration: Example 7 }}} }

Types of Result Sets 3-3


ResultSet rs = stmt.executeQuery("select * from friends "); import java.sql.SQLException; rs.moveToInsertRow(); import java.sql.Connection; It rs.updateString("Name", creates a result set object, rs, which is scrollable, "Jack"); import java.sql.DriverManager;"Tokyo"); rs.updateString("Address", updatable and sensitive to changes. import java.sql.Statement; rs.updateInt("salary", 65000); import java.sql.ResultSet; It rs.insertRow(); demonstrates the different steps followed to access a /**rs.beforeFirst(); This class demonstrates the different steps followed to access a database*/ database. System.out.println("Table FRIENDS after insertion:"); class Jdbctest { while (rs.next()) { /**String Constructor. name = */ rs.getString("Name"); protected Jdbctest() { String address = rs.getString("Address"); }/** This is a main method */ int salary = rs.getInt("Salary"); public static void main(final String [] args) { + salary); System.out.print(name + "\t" + address + "\t" try { System.out.println(" "); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } } catch (ClassNotFoundException ce) { rs.close(); System.out.println(ce);} stmt.close(); try { con.close(); String url = "jdbc:odbc:test"; } catch (SQLException ce) { Connection con = DriverManager.getConnection(url); ce.printStackTrace(); Statement stmt = con.createStatement( System.out.println(ce); ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); }}}

Demonstration: Example 8

Summary
Java Database Connectivity (JDBC) Application Programming Interface (API) is a part of the Java APIs provided by Sun Microsystems that 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. The driver is loaded into the Java interpreter using Class.forName() method. The driver is loaded into the java interpreter using the Class.forname method Establish a connection using the getConnection() method of DriverManager class and use the createStatement() method of the Connection object . Finally, SQL statements are constructed and executed through the statement instance by using either executeQuery() or executeUpdate() methods. The PreparedStatement interface allows us to create pre-compiled SQL statements and gives the option of specifying the parameters for the statement at a later stage. ResultSet can be scrollable or non scrollable and first(), last(), afterLast(), beforeFirst() are some of the methods for moving the cursor in result set.

Вам также может понравиться