Sei sulla pagina 1di 32

JAVA DATABASE CONNECTIVITY

Before JDBC, ODBC API was used to connect


and execute query to the database. But ODBC
API uses ODBC driver that is written in C
language which is platform dependent and
unsecured.
That is why Sun Microsystem has defined its
own API (JDBC API) that uses JDBC driver
written in Java language.
JDBC is a Java API that is used to connect and
execute query to the database. JDBC API uses
jdbc drivers to connects to the database.
API (Application programming interface) is a
document that contains description of all the
features of a product or software. An API can
be created for applications, libraries,
operating systems, etc
Standard Access to DB
A
P D DBMS
P Driver 1 DBMS 1 DB
R
L I
I V
C E
A R DBMS
T DBMS 2 DB
Driver 2
I M
O G
N R

DBMS
Driver 3
DBMS 3 DB
ODBC Architecture
Application

Class1 Class2

ODBC

Driver Manager

DriverType1 DriverType2 DriverType3

DataSource2 DataSource3
DataSource1

8/20/2017
Open Database Connectivity (ODBC)
Standard
ODBC standard is an interface by which application
programs can access and process SQL databases in a DBMS-
independent manner. It contains:
A Data Source is the database, its associated DBMS,
operating system and network platform
A DBMS Driver is supplied by the DBMS vendor or
independent software companies
A Driver Manager is supplied by the vendor of the O/S
platform where the application is running

8/20/2017
Application in Java

Application in
DriverManager
Java

Sybase driver mSQL driver Informix driver

8/20/2017
Java Support for ODBC : JDBC
When applications written in Java want to access
data sources, they use classes and associated
methods provided by Java DBC (JDBC) API.
JDBC is specified an an interface.
An interface in Java can have many
implementations.
So it provides a convenient way to realize many
drivers

8/20/2017
JDBC Drivers
JDBC-ODBC bridge
Native-API-Partly-Java driver
JDBC-Net pure Java:
100% pure Java
USAGE
If you are accessing one type of database, such as Oracle,
Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations where a type 3 or
type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level
driver and is typically used for development and testing
purposes only.

8/20/2017
JDBC Drivers
Java
application
JDBC-API
JDBC-
Driver manager

100% pure JDBC- JDBC-ODBC Native


Java Net-driver bridge API-driver
DB-
ODBC Client library
Middleware

Client library

8/20/2017
JDBC Components
Driver Manager: Loads database drivers and manages the
connection between application & driver.
Driver: Translates API calls to operations for a specific data
source.
Connection: A session between an application and a driver.
Statement: A SQL statement to perform a query or an update
operation.
Metadata: Information about the returned data, driver and
the database.
Result Set : Logical set of columns and rows returned by
executing a statement.

8/20/2017
JDBC Classes
Java supports DB facilities by providing classes
and interfaces for its components
DriverManager class
Connection interface (abstract class)
Statement interface (to be instantiated with
values from the actual SQL statement)
ResultSet interface

8/20/2017
JDBC Application Architecture
Application

Connection Statement Result Set

Driver Manager

Driver Driver Driver

DataSource DataSource
DataSource

8/20/2017
JDBC Programming Steps
Import package: import java.sql.* ; // for
standard JDBC programs
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection

8/20/2017
Register the driver class
The forName() method of Class class is used to
register the driver class. This method is used
to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)
throws ClassNotFoundException
Example to register the MySqlDriver class
Class.forName("com.mysql.jdbc.Driver");
Driver class for mysql database is com.mysql.jdbc.Driver
Create the connection object
The getConnection() method of DriverManager class is used to
establish connection with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws
SQLException
2) public static Connection getConnection(String url,String name,
String password) throws SQLException

Example
Connection con=DriverManager.getConnection( "jdbc:mysql://
localhost/EMP",usename","password");
Database URL Formulation: This is to create a
properly formatted address that points to the
database to which you wish to connect.
Create Connection Object: Finally, code a call
to the DriverManager object's getConnection(
)method to establish actual database
connection.
Create the Statement object
The createStatement() method of Connection
interface is used to create statement. The
object of statement is responsible to execute
queries with the database. Syntax of
createStatement() method
public Statement createStatement()
throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
Interfaces Recommended Use
Statement Use for general-purpose access to your database. Useful
when you are using static SQL statements at runtime.
The Statement interface cannot accept parameters.

PreparedStatement Use when you plan to use the SQL statements many
times. The PreparedStatement interface accepts input
parameters at runtime.

CallableStatement Use when you want to access database stored


procedures. The CallableStatement interface can also
accept runtime input parameters.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
Statement stmt=con.createStatement();

//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");


//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 wh
ere id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ?
WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...}
catch (SQLException e) { . . . }
finally { . . . }
package com.java2novice.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MyPreparedStatement {
public static void main(String a[]){
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB
name>" ,"user","password");
String query = "insert into emp(name,salary) values(?,?)";
prSt = con.prepareStatement(query);
prSt.setString(1, "John");
prSt.setInt(2, 10000);
int count = prSt.executeUpdate();
prSt.setString(1, "Cric");
prSt.setInt(2, 5000);
count = prSt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}}}
Execute the query
The executeQuery() method of Statement interface is used to execute
queries to the database. This method returns the object of ResultSet
that can be used to get all the records of a table.
Syntax of executeQuery() method

public ResultSet executeQuery(String sql) throws SQLException

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
The methods of the ResultSet interface can be
broken down into three categories:
Navigational methods: used to move the cursor
around.
Get methods: used to view the data in the
columns of the current row being pointed to by
the cursor.
Update methods: used to update the data in the
columns of the current row. The updates can then
be updated in the underlying database as well.
For inserting, updating and deleting
data in database

String sql = "CREATE DATABASE STUDENTS";


stmt.executeUpdate(sql);
Close the connection object
By closing connection object statement and
ResultSet will be closed automatically. The
close() method of Connection interface is
used to close the connection. Syntax of
close() method
public void close()throws SQLException
Example to close connection
con.close();
Running a JDBC Application

Phase Task Relevant java.sql classes

Initialisation Load driver DriverManager


Create connection Connection

Processing Generate SQL statements Statement


Process result data ResultSet etc.

Terminate connection Connection


Termination
Release data structures Statement etc.

8/20/2017
A Simple JDBC application
import java.sql.*;
public class jdbctest {
loadDriver
public static void main(String args[]){
getConnection
try{
Class.forName("org.postgresql.Driver");
createStatement Connection con = DriverManager.getConnection
("jdbc:postgresql://lsir-cis-pc8:5401/pcmdb", "user", "passwd");
execute(SQL) Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
Result handling ("select name, number from pcmtable where number < 2");
yes while(rs.next())
System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")");
More
results ? stmt.close()
con.close();
no
} catch(Exception e){
closeStatment
System.err.println(e);
closeConnection }}}
8/20/2017
Identifying Data Sources
It is specified using URL format.
<scheme>: <sub_scheme>:<scheme-specific-part>
Example(for local source): jdbc:odbc:tech_books
Alternatively, for remote connection,
jdbc:odbc://bina.cse.buffalo.edu:4333/tech_books

8/20/2017
Connectivity with MySQL
first create a table in the mysql database, but
before creating table, we need to create
database first.
create database db;
use db;
create table emp(id int(10),name varchar(40),
age int(3));
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db","root","root");

//here db is database name, root is username and password

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}


}
}
To connect java application with the mysql
database mysqlconnector.jar file is required to be
loaded.

http://dev.mysql.com/downloads/connector/j/

paste the mysqlconnector.jar file in jre/lib/ext


folder
REFER MORE PROGRAMS ON TUTORIALPOINTS
WEBSITE

Potrebbero piacerti anche