Java Unit-3 Lecture-30 31
Java Unit-3 Lecture-30 31
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.
• JDBC Driver is a software component that enables java application to interact with the
database.
• 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.
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
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
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");
Statement stmt=con.createStatement();
con.close();
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");
con.close();
}}
PreparedStatement interface
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.
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");
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
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;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracl
e");
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.
• 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?
38
References
Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .
39
THANK YOU
For queries
Email: kushagra.e13465@cumail.in