Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views

Java Unit-3 Lecture-30 31

This document provides information about database connectivity in Java using JDBC. It discusses the key classes and interfaces in JDBC like Driver, Connection, Statement, PreparedStatement, and ResultSet. It describes the 5 steps to connect to a database - register driver, get connection, create statement, execute query, and close connection. Examples are provided to demonstrate connecting to an Oracle database, executing queries, retrieving results, and using prepared statements. The goal is to teach students how to connect Java applications to a database.

Uploaded by

aasthabansal1803
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Java Unit-3 Lecture-30 31

This document provides information about database connectivity in Java using JDBC. It discusses the key classes and interfaces in JDBC like Driver, Connection, Statement, PreparedStatement, and ResultSet. It describes the 5 steps to connect to a database - register driver, get connection, create statement, execute query, and close connection. Examples are provided to demonstrate connecting to an Oracle database, executing queries, retrieving results, and using prepared statements. The goal is to teach students how to connect Java applications to a database.

Uploaded by

aasthabansal1803
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

UNIVERSITY INSTITUTE OF ENGINEERING

DEPARTMENT OF AIT - CSE


Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)

Lecture -30 &31 DISCOVER . LEARN . EMPOWER


DATABASE Connectivity in JAVA
Chapter Course Objectives

● To understand about Database.


20. ● To understand about Database connectivity with java.

Chapter Course Outcomes

After completion of this course, student will be able to


● Learn about the database.
20. ● Learn about Database connectivity with java.

2
Data Base Connectivity in JAVA
Java JDBC
• JDBC stands for Java Database Connectivity.
• JDBC is a Java API to connect and execute the query with the database.
• It is a part of JavaSE (Java Standard Edition).
• JDBC API uses JDBC drivers to connect with the database.

There are four types of JDBC drivers:


• JDBC-ODBC Bridge Driver(Type1)
• Native Driver(Type2)
• Network Protocol Driver(Type3)
• Thin Driver(Type4)
Java JDBC
• The java.sql package contains classes and interfaces for JDBC API.
A list of popular interfaces of JDBC API are given below:
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
JDBC Driver

• JDBC Driver is a software component that enables java application to interact with the
database.

There are 4 types of JDBC drivers:


• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method
calls into the ODBC function calls. This is now discouraged
because of thin driver.
2) Native-API driver
• The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
3) Network Protocol driver
• The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.
4) Thin driver
• The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.
Java Database Connectivity with 5 Steps

• There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
1) 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

Ex:
• Class.forName("oracle.jdbc.driver.OracleDriver");
2) 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

Ex:
• Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) 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

Ex:
• Statement stmt=con.createStatement();
4) 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
Ex:
• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next())
• {
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• }
5) 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
Ex:
• con.close();
Java Database Connectivity with Oracle

Create a Table
• Before establishing connection, let's first create a table in oracle database.
• Following is the SQL query to create a table.
• create table emp(id number(10),name varchar2(40),age number(3))
;
Ex:Database Connectivity

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

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);}


} }
Statement interface
• The Statement interface provides methods to execute queries with the database.

The important methods of Statement interface are as follows:


1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It
returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may
be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
ResultSet interface
• The object of ResultSet maintains a cursor pointing to a row of a table.
• Initially, cursor points to before the first row.
1) public boolean next(): is used to move the cursor to the one row next from the current position.

2) public boolean previous(): is used to move the cursor to the one row previous from the current position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object.

6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or
negative.

7) public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int.

8) public int getInt(String columnName): is used to return the data of specified column name of the current row as int.

9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String.

10) public String getString(String columnName): is used to return the data of specified column name of the current row as String.
Ex:ResultSet
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","oracl
e");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_U
PDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}
PreparedStatement interface

• The PreparedStatement interface is a subinterface of Statement.


• It is used to execute parameterized query.
Example of parameterized query:
• String sql="insert into emp values(?,?,?)";

Method Description

public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.

public void setString(int paramIndex, String value) sets the String value to the given parameter index.

public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.

public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.
Ex:PreparedStatement
First of all create table as given below:
create table emp(id number(10),name varchar2(50));

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);} } }
Java ResultSetMetaData Interface
• The metadata means data about data i.e. we can get further information from the data.
• If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.
Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.

public String getColumnName(int index)throws it returns the column name of the specified column
SQLException index.

public String getColumnTypeName(int index)throws it returns the column type name for the specified
SQLException index.

public String getTableName(int index)throws it returns the table name for the specified column
SQLException index.
Ex:ResultSetMetaData
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
store image in Oracle database

• You can store images in the database in java by the help of PreparedStatement interface.
• The setBinaryStream() method of Prepared Statement is used to set Binary information into the
parameter Index.

Methods:
1) public void setBinaryStream(int paramIndex,InputStream stream) throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream, long length) throws SQLException
Ex: Image Store
• For storing image into the database, BLOB (Binary Large Object) data type is used in the table.
For example:
• CREATE TABLE "IMGTABLE" ( "NAME" VARCHAR2(4000), "PHOTO" BLOB )

import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle")
PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
ps.setString(1,“Dog");
FileInputStream fin=new FileInputStream("d:\\g.jpg");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();} } }
CallableStatement Interface

• CallableStatement interface is used to call the stored procedures and functions.

Syntax:
• public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

Ex:
• CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
Ex:
To call the stored procedure, you need to create it in the database. Here, we are assuming that
stored procedure looks like this.
create or replace procedure "INSERTR"
(id IN NUMBER,name IN VARCHAR2)
is begin
insert into user values(id,name);
end;

The table structure is given below:


create table user420(id number(10), name varchar2(200));
Ex:(cont..)
import java.sql.*;
public class Proc {
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","oracl
e");

CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");


stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();

System.out.println("success");
}
}
Singleton Class
Singleton design pattern in Java

• Singleton Pattern says that just"define a class that has only one instance and
provides a global point of access to it".
• In other words, a class must ensure that only single instance should be created
and single object can be used by all other classes.

There are two forms of singleton design pattern:


• Early Instantiation: creation of instance at load time.
• Lazy Instantiation: creation of instance when required.
Singleton design pattern in Java
Advantage of Singleton design pattern
• Saves memory because object is not created at each request.
• Only single instance is reused again and again.

Usage of Singleton design pattern


• Singleton pattern is mostly used in multi-threaded and database applications.
• It is used in logging, caching, thread pools, configuration settings etc.
How to create Singleton design pattern?

• To create the singleton class, we need to have static member of class, private constructor and
static factory method.
• Static member: It gets memory only once because of static, it
contains the instance of the Singleton class.
• Private constructor: It will prevent to instantiate the Singleton class
from outside the class.
• Static factory method: This provides the global point of access to
the Singleton object and returns the instance to the caller.
Ex:1
• class A{
• private static A obj=new A();//Early, instance will be created at load time
• private A(){}

• public static A getA(){
• return obj;
• }

}
Ex:2
• class A{
• private static A obj;
• private A(){}
• public static A getA(){
• if (obj == null){
• synchronized(Singleton.class){
• if (obj == null){
• obj = new Singleton();//instance will be created at request time
• }
• }
• return obj;
•}
Summary
. Discussed about Database.
. Discussed different types database connectivity with java.

37
Home Work
Q1. What is JDBC Driver?

Q2. What are the steps to connect to the database in java?

38
References

Online Video Link


• https://nptel.ac.in/courses/106/105/106105191/
• https://www.coursera.org/courses?query=java
• https://www.coursera.org/specializations/object-oriented-programming
• https://www.youtube.com/watch?v=aqHhpahguVY

Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .

39
THANK YOU

For queries
Email: kushagra.e13465@cumail.in

You might also like