0% found this document useful (0 votes)
83 views

Unit - 2 JDBC

The document discusses Java Database Connectivity (JDBC) which provides a standard interface for connecting Java applications to different database systems. It describes the key components of JDBC including the DriverManager, Connection, Statement, and ResultSet classes. It also outlines the basic steps to create a JDBC application such as importing packages, registering a JDBC driver, opening a connection, executing queries, extracting result sets, and closing resources.

Uploaded by

srinivas890
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Unit - 2 JDBC

The document discusses Java Database Connectivity (JDBC) which provides a standard interface for connecting Java applications to different database systems. It describes the key components of JDBC including the DriverManager, Connection, Statement, and ResultSet classes. It also outlines the basic steps to create a JDBC application such as importing packages, registering a JDBC driver, opening a connection, executing queries, extracting result sets, and closing resources.

Uploaded by

srinivas890
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Java 

Database Connectivity

Mahesh K
Syllabi
• DATABASE CONNECTIVITY: JDBC perspectives,
JDBC program example
JDBC stands for Java Database Connectivity, which
is a standard Java API for database-independent
connectivity between the Java programming
language and a wide range of databases.

The JDBC library includes APIs for each of the tasks


mentioned below that are commonly associated
with database usage.

•Making a connection to a database.


•Creating SQL or MySQL statements.
•Executing SQL or MySQL queries in the database.
•Viewing & Modifying the resulting records.
JDBC is a specification that provides a complete set
of interfaces that allows for portable access to an
underlying database. Java can be used to write
different types of executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a
JDBC driver to access a database, and take
advantage of the stored data.
JDBC Architecture
The JDBC API supports both two-tier and three-tier
processing models for database access but in general,
JDBC Architecture consists of two layers −
• JDBC API: This provides the application-to-JDBC Manager
connection.
• JDBC Driver API: This supports the JDBC Manager-to-
Driver Connection.
The JDBC API uses a driver manager and database-specific
drivers to provide transparent connectivity to
heterogeneous databases.
The JDBC driver manager ensures that the correct driver is
used to access each data source. The driver manager is
capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
architectural diagram
Common JDBC Components
• The JDBC API provides the following interfaces and
classes −
• DriverManager: This class manages a list of database
drivers. Matches connection requests from the java
application with the proper database driver using
communication sub protocol. The first driver that
recognizes a certain subprotocol under JDBC will be used
to establish a database Connection.
• Driver: This interface handles the communications with
the database server. You will interact directly with Driver
objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also
abstracts the details associated with working with Driver
objects.
Common JDBC Components
• Connection: This interface with all methods for
contacting a database. The connection object represents
communication context, i.e., all communication with
database is through connection object only.
• Statement: You use objects created from this interface to
submit the SQL statements to the database. Some
derived interfaces accept parameters in addition to
executing stored procedures.
• ResultSet: These objects hold data retrieved from a
database after you execute an SQL query using Statement
objects. It acts as an iterator to allow you to move
through its data.
• SQLException: This class handles any errors that occur in
a database application.
Creating JDBC Application
There are following six steps involved in building a JDBC application
• Import the packages: Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so
you can open a communication channel with the database.
• Open a connection: Requires using the
DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with the database.
• Execute a query: Requires using an object of type Statement for
building and submitting an SQL statement to the database.
• Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.
• Clean up the environment: Requires explicitly closing all database
resources versus relying on the JVM's garbage collection.
What is JDBC Driver
JDBC drivers implement the defined interfaces in the
JDBC API, for interacting with your database server.
For example, using JDBC drivers enable you to open
database connections and to interact with it by
sending SQL or database commands then receiving
results with Java.
The Java.sql package that ships with JDK, contains
various classes with their behaviors defined and their
actual implementations are done in third-party
drivers.
Third party vendors implements the
 java.sql.Driver interface in their database driver.
JDBC Drivers Types
• JDBC driver implementations vary because of the
wide variety of operating systems and hardware
platforms in which Java operates. Sun has divided
the implementation types into four categories,
Type 1,
Type 2,
Type 3, and
Type 4
Import JDBC Packages
• The Import statements tell the Java compiler
where to find the classes you reference in
your code and are placed at the very
beginning of your source code.

import java.sql.* ; // for standard JDBC programs


Register JDBC Driver
• You must register the driver in your program
before you use it. Registering the driver is the
process by which the Oracle driver's class file is
loaded into the memory, so it can be utilized as
an implementation of the JDBC interfaces.
• You need to do this registration only once in
your program.
• You can register a driver in one of two ways.
Approach I - Class.forName()
• The most common approach to register a driver is
to use Java's Class.forName() method, to
dynamically load the driver's class file into memory,
which automatically registers it. This method is
preferable because it allows you to make the driver
registration configurable and portable.
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); }
catch(ClassNotFoundException ex)
{ System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Approach II -
DriverManager.registerDriver()
• The second approach you can use to register a driver, is
to use the static
DriverManager.registerDriver() method.
• You should use the registerDriver() method if you are
using a non-JDK compliant JVM, such as the one
provided by Microsoft.
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
} catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Database URL Formulation
After you've loaded the driver, you can establish a
connection using the
DriverManager.getConnection() method.
DriverManager.getConnection() methods −
• getConnection(String url)
• getConnection(String url, Properties prop)
• getConnection(String url, String user, String password)
• Here each form requires a database URL. A database URL
is an address that points to your database.
• Formulating a database URL is where most of the problems
associated with establishing a connection occurs.
Execute an SQL statement
• The Statement interface is used to execute
static SQL statements.
• A Statement object is instantiated using the
createStatement() method on the Connection
object.

Statement stmt = con.createStatement();


try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:dsn");
Statement st = con.createStatement();
st.executeUpdate("create table emp(eno number,ename varchar(10),sal
number)");

st.close();
con.close();
}
Methods of Statement object
• executeUpdate()
– Used to execute DDL (CREATE, ALTER, and DROP).
DML (INSERT, DELETE, UPDATE, etc) and DCL
statements
– The return value of this method is the number of
rows affected.

st.executeUpdate("create table emp(eno


number,ename varchar(10),sal number)");
Methods of Statement object
• executeQuery()
– Used to execute DQL statements such as SELECT.
– DQL statements only read data from database
tables.
– The return value of this method is a set of rows,
represented as a ResultSet object.

st.executeUpdate("create table emp(eno


number,ename varchar(10),sal number)");
import java.sql.*; Ex-1: Create Table

public class CreateTable


{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:dsn");
Statement st = con.createStatement();
st.executeUpdate("create table employee(eno number,ename varchar(10),sal number)");

st.close();
con.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException cnfe)
{
System.exit(1);
}
}
}
import java.sql.*; Ex-2: Insert into Table
import java.io.*;

class IncorrectChoiceException extends Exception


{
}
public class InsertTable
{
public static void main(String args[])throws ClassNotFoundException, IOException
{
int i = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");
Statement st = con.createStatement();
boolean wantMore = true;
while(wantMore)
{
System.out.print("Enter employee number : ");
int eno = Integer.parseInt(br.readLine());
System.out.print("Enter name : ");
String ename = br.readLine();
System.out.print("Enter salary : ");
double sal = Double.parseDouble(br.readLine());

i += st.executeUpdate("insert into employee values(" + eno + ", \'" + ename + "\'," + sal + ")");

System.out.print("\nDo you want ot enter more records? (Y/N) : ");


String choice = br.readLine();

if(choice.equals("N") || choice.equals("n"))
wantMore = false;
else if(choice.equals("Y") || choice.equals("y"))
wantMore = true;
else throw new IncorrectChoiceException();
}
System.out.println("Update success : "+i+" rows updated");
st.close();
con.close();
}
catch(SQLException se){
se.printStackTrace(); }
catch(IncorrectChoiceException ic){
System.out.println("Error : Incorrect choice");}
finally{
System.out.println("Total updates performed : "+i);}
}}
import java.sql.*; Ex-3: Update Table
import java.io.*;

public class UpdateTable


{
public static void main(String s[ ])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");
Statement st=con.createStatement();
con.setAutoCommit(false);

int i1=st.executeUpdate("update employee set sal=sal+1500 where eno=1");


int i2=st.executeUpdate("update employee set sal=sal+1000 where eno=2");

con.commit();
con.close();
}
catch(Exception e)
{
//con.RollBack();
e.printStackTrace();
}
}
}
import java.sql.*; Ex-4: Prepared statements
import java.io.*;
public class PreparedStmts {
public static void main(String s[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");

PreparedStatement ps=con.prepareStatement("select * from employee where empno=?");


BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter empno:");
int empno=Integer.parseInt(b.readLine());
if(empno==0)
break;
ps.setInt(1,empno);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println("ENAME: "+rs.getString(2));
System.out.println("SALARY: "+rs.getString(3));
}
rs.close();
}
con.close();
}
catch(Exception e) {
System.out.println("The Exception is...."+e); }
}}
END

You might also like