Download www.hndit.com Introduction to JDBC JDBC is a simple API for

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Concurrency control wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft Access wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Functional Database Model wikipedia , lookup

Ingres (database) wikipedia , lookup

Database wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

SQL wikipedia , lookup

Versant Object Database wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

PL/SQL wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Transcript
www.hndit.com
Introduction to JDBC
 JDBC is a simple API for connecting from Java applications to multiple databases.
 Lets you smoothly translate between the world of the database, and the world of the Java application.
 The idea of a universal database access API is not a new one. For example, Open Database Connectivity
(ODBC) was developed to create a single standard for database access in the Windows environment.
 JDBC API aims to be as simple as possible while providing developers with maximum flexibility.
JDBC Main features





Provides a set of classes for java with a standard SQL database access interface.
Uniform access to wide range of relational database s.
Provides an API for database “drivers” to make actual connections & transaction to database products.
Includes JDBC-ODBC bridge to standard ODBC drivers.
JDBC is a “low- level” interface, calling SQL commands directly but is meant to be a base for higherlevel Interfaces
Traditional web/ RDBMS access





Traditional web access to the db was done with the use of CGI (Common Gateway Interface) Script
accessing the db and creating output in the form of HTML document presented in www client.
The requests and responses were transmitted using http protocol.
No session notification
Unable to preserve the db transaction logic.
JDBC Software Architecture
JDBC expands these options
 Java programs can be executed on client and on server side. In this case it is possible to
create 3- tier client server application.
 Client application can also access DB directly.
Result set
Result set
Result set
Statement
Prepared statement
Prepared statement
Connection
Driver Manager
Oracle driver
Oracle DB
JDBC ODBC
Bridge
Access DB
Sybase Drive
Sybase DB
1
www.hndit.com
Understanding JDBC Drivers



To connect to a database, you first need a JDBC Driver.
JDBC Driver: set of classes that interface with a specific database engine.
JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, MySQL, etc...
JDBC Driver Types




Type 1 : JDBC –ODBC bridge
Type 2 : Native-API/Partly Java
driver
Type 3 : Net-protocol / All –Java
Driver
Type 4 : Native-protocol / All Java
Driver
Type 1 & 2 rely on native binary modules.

Platform specific

Cannot be used for applets
Type 3 & 4 are 100% Java
Type 1 Driver
 JDBC-ODBC Bridge
o Translate all JDBC calls into ODBC
(Open DataBase Connectivity)
 Need to have ODBC client installed on the
machine.
Client machine
JDBC-ODBC Bridge
ODBC Driver
Server machine
DB Server
Vendor DB library
Type 2 Driver - Native-API/Partly Java driver
 Converts JDBC calls into DB specific calls.
 Communicates directly with the DB server.
 Requires some binary code be present on the
client machine.
 Better performance than type 1 driver.
Client machine
Server machine
Native-API/Partly
Java driver
Vendor DB library
DB Server
Type 3 Driver
 Net-protocol / All –Java Driver – 100% Java
 Follows a three tier approach.
2
o
o
JDBC db requests passed to the middle tier server.
Middle tier server translates the request to the db specific native connectivity interface.
 May use type 1 or type 2 JDBC driver.
Request forded to the db server.
o
Client machine
Net-protocol
driver
Server machine
Middleware machine
Middleware
server
DB Server
Type 4 Driver
 Native-protocol 100% Java
 Converts JDBC calls into vender specific
DBMS protocol.
 Client applications communicate directly with
the DB server
 Best performance.
 Need a different driver for each DB.
Client machine
Server machine
Native protocol
driver
DB Server
JDBC Package

The JDBC API is contained in jdk 1.1 onwards.

Uses many interfaces, allowing driver to supply the implementation.

The JDBC API is contained in two packages.
o java.sql
-contains core java database objects of the JDBC API. Part of the J2SE
o javax.sql
-extends java.sql and is in the J2EE
JDBC API
Interfaces
CollableStatement
Connection
DatabaseMetaData
Driver
PreparedStatement
ResultSet
ResultSetMetaData
Statement
Classes
Date
DriverManager
DriverPropertyInfo
Numeric
Time
Timestamp
Types
Exceptions
SQLException
SQLWarning
DataTruncation
Six Steps to Using JDBC
1.
Load the JDBC Driver
2.
Establish the Database Connection
3.
Create a Statement Object
4.
Execute a Query
5.
Process the Results
6.
Close the Connection
1)
Loading the JDBC Driver
 To use a JDBC driver, you must load the driver via the Class.forName() method.
 In general, the code looks like this:
Class.forName("jdbc.DriverXYZ");
where jbdc.DriverXYZ is the JDBC Driver you want to load.
3
 If you are using a JDBC-ODBC Driver, your code will look like this:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
www.hndit.com
Loading the ODBC Driver
 If you are using the ODBC Driver, your code will look like this:
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
 Class.forName() will throw a ClassNotFoundException if your CLASSPATH is not set up properly.
 Hence, it's a good idea to surround the forName() with a try/catch block.
2)
Establish the Connection
 Once you have loaded your JDBC driver, the next step is to establish a database connection.
 The following line of code illustrates the basic idea:
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
 In general, the URL has the following format: jdbc:subprotocol:subname.
 JDBC indicates that this is a JDBC Connection.
 The subprotocol identifies the driver you want to use.
 The subname identifies the database name/location.
 For example, the following code uses a JDBC-ODBC bridge to connect to the local stud database:
String url = "jdbc:odbc:stud";
Connection con = DriverManager.getConnection(url, "Deepani", "password");
 In this case, we are using the Access JDBC Driver to connect to the studt database, located on the
localhost machine.
 If this code executes successfully, we will have a Connection object for communicating directly with the
database.
3) Create a Statement Object
 The JDBC Statement object sends SQL statements to the database.
 Statement objects are created from active Connection objects.
 For example:
Statement stmt = con.createStatement();
 With a Statement object, you can issue SQL calls directly to the database.
4) Execute a Query
 executeQuery()
 Executes the SQL query and returns the data in a table (ResultSet)
 The resulting table may be empty but never null
ResultSet results = stmt.executeQuery("SELECT a, b FROM tableName");
 executeUpdate()

Used to execute for INSERT, UPDATE, or DELETE SQL statements


The return is the number of rows that were affected in the database
Supports Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE
and ALTER TABLE
4
www.hndit.com
Useful Statement Methods
 getMaxRows/setMaxRows
 Determines the number of rows a ResultSet may contain
 Unless explicitly set, the number of rows are unlimited (return value of 0)
 getQueryTimeout/setQueryTimeout
 Specifies the amount of a time a driver will wait for a STATEMENT to complete before throwing a
SQLException
5.) Process the Results
ResultSet
 An object providing access to a table of data generated by a Statement.
 The table rows are retrieved in sequence.
 Within a row, column values can be accessed in any order.
 A ResultSet maintains a cursor pointing to its current row of data.
 Initially the cursor is positioned before the first row.
 The next() method moves the cursor to the next row.
 When no more rows next() returns false.
 A ResultSet contains the results of the SQL query.
Useful Methods
All methods can throw a SQLException
close
 Releases the JDBC and database resources
 The result set is automatically closed when the associated Statement object executes a new query
getMetaDataObject
Returns a ResultSetMetaData object containing information about the columns in the ResultSet
next
 Attempts to move to the next row in the ResultSet
o If successful true is returned; otherwise, false
o The first call to next positions the cursor a the first row
findColumn
 Returns the corresponding integer value corresponding to the specified column name
 Column numbers in the result set do not necessarily map to the same column numbers in the database
getXxx
 Returns the value from the column specified by column name or column index as an Xxx Java type
 Returns 0 or null, if the value is a SQL NULL
 Can takes arguments by Column labels or Column position number.
Legal getXxx types:
double
byte
int
Date
String
float
short
long
Time
Object
Eg :
String name = uprs.getString("COF_NAME");
int id = uprs.getInt("SUP_ID");
6.)
Close the Connection
To close the database connection:
a.
stmt.close();
b.
connection.close();
Note: Some application servers, such as BEA WebLogic maintain a pool of database connections.
This is much more efficient, as applications do not have the overhead of constantly opening and closing
database connections
5
www.hndit.com
Example
Setting Up Tables via JDBC
The Coffee Tables
 Here’s the SQL Statement to create a table for storing data:
CREATE TABLE COFFEES
(COF_NAME VARCHAR(32),
SUP_ID INTEGER,
PRICE FLOAT,
SALES INTEGER,
TOTAL INTEGER);
The Coffee Table
A few things to note about the table:
 The column named SUP_ID contains an integer value indicating a Supplier ID.
 Suppliers will be stored in a separate table. In this case, SUP_ID is referred to as a foreign key.
 The column named SALES stores values of SQL type INTEGER and indicates the number of
pounds of coffee sold during the current week.
 The final column, TOTAL, contains a SQL INTEGER which gives the total number of pounds of
coffee sold to date.
import java.sql.*;
public class CreateCoffees {
public static void main(String args[]) {
String url = "jdbc:odbc:stud";
Connection con;
String createString;
createString = "create table COFFEES " +
"(COF_NAME VARCHAR(32), " +
"SUP_ID INTEGER, " +
"PRICE FLOAT, " +
"SALES INTEGER, " +
"TOTAL INTEGER)";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url);
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
6
www.hndit.com
Example 2:
//Inserting Data via JDBC
import java.sql.*;
public class InsertCoffees {
public static void main(String args[]) throws SQLException {
System.out.println ("Adding Coffee Data");
ResultSet rs = null;
PreparedStatement ps = null;
String url = "jdbc:odbc:stud";
Connection con;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url);
stmt = con.createStatement();
stmt.executeUpdate ("INSERT INTO COFFEES " +
"VALUES('Amaretto', 49, 9.99, 0, 0)");
stmt.executeUpdate ("INSERT INTO COFFEES " +
"VALUES('Hazelnut', 49, 9.99, 0, 0)");
stmt.executeUpdate ("INSERT INTO COFFEES " +
"VALUES('Amaretto_decaf', 49, 10.99, 0, 0)");
stmt.executeUpdate ("INSERT INTO COFFEES " +
"VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");
stmt.close();
con.close();
System.out.println ("Done");
} catch(SQLException ex) {
System.err.println("-----SQLException-----");
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("Message: " + ex.getMessage());
System.err.println("Vendor: " + ex.getErrorCode());
}
}
}
//Querying Data via JDBC
import java.sql.*;
public class SelectCoffees {
public static void main(String args[]) throws SQLException {
ResultSet rs = null;
PreparedStatement ps = null;
String url = "jdbc:odbc:stud";
Connection con;
7
www.hndit.com
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url);
stmt = con.createStatement();
ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");
System.out.println("Table COFFEES:");
while (uprs.next()) {
String name = uprs.getString("COF_NAME");
int id = uprs.getInt("SUP_ID");
float price = uprs.getFloat("PRICE");
int sales = uprs.getInt("SALES");
int total = uprs.getInt("TOTAL");
System.out.print(name + " " + id + " " + price);
System.out.println(" " + sales + " " + total);
}
uprs.close();
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("-----SQLException-----");
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("Message: " + ex.getMessage());
System.err.println("Vendor: " + ex.getErrorCode());
}
}
}
Output
Table COFFEES:
Amaretto 49 9.99 0 0
Hazelnut 49 9.99 0 0
Amaretto_decaf 49 10.99 0 0
Hazelnut_decaf 49 10.99 0 0
JDBC Exception Handling
SQL Exceptions
 Nearly every JDBC method can throw a SQLException in response to a data access error
 If more than one error occurs, they are chained together
 SQL exceptions contain:
 Description of the error, getMessage
 The SQLState (Open Group SQL specification) identifying the exception, getSQLState
 A vendor-specific integer, error code, getErrorCode
 A chain to the next SQLException, getNextException
8
www.hndit.com
SQL Exception Example
try {
... // JDBC statement.
} catch (SQLException sqle) {
while (sqle != null) {
System.out.println("Message: " + sqle.getMessage());
System.out.println("SQLState: " + sqle.getSQLState());
System.out.println("Vendor Error: " +
sqle.getErrorCode());
sqle.printStrackTrace(System.out);
sqle = sqle.getNextException();
}
}
Meta Data
 The java.sql package contains two meta data interfaces, the DataBaseMetaData and the
ResultSetMetaData interface.
 The DataBaseMetaData interface is used to obtain information about a DB such as list of all tables in the
DB, system functions, the name of the jdbc driver, etc.
 The resultSetMetaData interface is used to obtain information about the Colum stored in a resultset object
such as the data type, the column heading & properties of its column.
 Meta data that describes the ResultSet is retrieved by calling the getMetaData() method of the ResultSet
object.This returns a ResultSetMetaData object, as follows:
ResultSetMetaData r = result.getMetaData()
Some methods of the ResultSetMetaData interface.
1. int getColumnCount ()
Returns the no-of columns stored in the resultSet object.
2. String getColumnName (int x)
Returns the name of the column specified by the column number.
3. String getColumTypeName (int x)
Returns a DB specific data type of the specified columns.
There are many other methods used to retrieve practically any information you need to know about a
database and ResultSet.
Eg:
ResultSetMetaData r = result.getMetaData()
int c = r.getColumn count ()
for (int i = 1, i< = c, i ++)
{
Syste.out.println (r.getColumnName(i));
}
Some methods of the DataBaseMetaData interface.
getDataBaseProductName()
getUserName()
getURL()
getPrimaryKeys()
getTables(0
etc.
A J2EE component retrieves meta data about the database by calling getMetaData() method of the
connection object. The getMetaData() returns DatabaseMetaData object that contains information about the
database and its components.
9
www.hndit.com
Prepared Statements
PreparedStatement objects are used to send SQL commands to the db.This object allows you to executed
parameterize quarries.
Reasons for using prepared Statements.
PreparedStatement objects are useful in several situations:
When you are working with different db systems.
When you are sending many SQL commands to the db, and only the data values are changing.
When you need to insert nonprimitive data in to table
Users supply the student it wants to see the details of the student.
Select * From Student where stuNo=?”;
to submit such parameter queries to a DB from an application prepare a query statement at runtime return
appropriate value in the where clause. The prepared Statement Object is created using the prepare Statement
() of the connection object.
Statement st = c.createStatement();
PrepairedStatement st1 = c.prepareStatement (“select * from student where stu_no = ?”);
The prepareStatement () takes the sql statement as a parameter the sql statement an contain place holders
that can be replaced by input parameters at runtime. The ? symbol is a place holders that can be replaced by
the input parameter at run time. Before executing a preparedStatement object you must set the value of each
? Parameter. This is done by calling an appropriate set xxx()
10