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

CH3 - JDBC – Java Database Connectivity

JDBC (Java Database Connectivity) is a Java API that enables communication between Java applications and databases, allowing for connection, query execution, and result retrieval. It consists of various components including the JDBC API, DriverManager, and JDBC drivers, which facilitate the interaction with different databases. The document also outlines the steps for connecting to a database, executing queries using Statement and PreparedStatement objects, and retrieving metadata about the database and result sets.

Uploaded by

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

CH3 - JDBC – Java Database Connectivity

JDBC (Java Database Connectivity) is a Java API that enables communication between Java applications and databases, allowing for connection, query execution, and result retrieval. It consists of various components including the JDBC API, DriverManager, and JDBC drivers, which facilitate the interaction with different databases. The document also outlines the steps for connecting to a database, executing queries using Statement and PreparedStatement objects, and retrieving metadata about the database and result sets.

Uploaded by

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

UNIT 3: JDBC – Java Database Connectivity

JDBC stands for Java Database Connectivity.

 JDBC is a Java API to connect and execute the query with the database.
 This API contains a set of classes and interfaces to enable programmers to communicate with a
database using java. JDBC classes and interfaces are in the java.sql package.
 We can use JDBC API to handle database using Java program and can perform the following
activities:
 Connect to the database
 Execute queries and update statements to the database
 Retrieve the result received from the database.

What is API?
API (Application programming interface) is a document that contains a description of all the features of a
product or software. It represents classes and interfaces that software programs can follow to
communicate with each other. An API can be created for applications, libraries, operating systems, etc.

Components of JDBC/ JDBC Architecture:

 Application: It is the Java servlet or an applet that communicates with the data source.
 JDBC API: JDBC API provides various interfaces and methods to establish easy connection with
different databases. It allows the Java programs to perform the execution of the SQL statements and
then get the results.
 DriverManager: DriverManager plays a crucial role in the architecture of JDBC. It uses database-
specific drivers to connect the enterprise applications to various databases. JDBC Driver
manager loads the database-specific driver into an application in order to establish the
connection with the database. The JDBC Driver manager is also used to make the database-specific
call to the database in order to do the processing of a user request.
 JDBC drivers: To interact with a data source with the help of the JDBC, one needs a JDBC driver
which conveniently interacts with the respective data source.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:
 Type1: JDBC-ODBC bridge driver
 Type2: Native-API driver (partially java driver)
 Type3: Network Protocol driver (fully java driver)
 Type4: Thin driver (fully java driver)

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.

Note: the JDBC-ODBC Bridge has been removed in Java 8.

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.

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.
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 Steps


There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
1. Register the Driver class/Load driver
2. Create connection
3. Create statement
4. Execute queries
5. Close (statement, resultset,) connection

Load Driver
For postgresql, use the driver :org.postgresql.Driver

To load the driver, use the following command:


Syntax :Class.forName(“DiverName”);
Example :Class.forName(“org.postgresql.Driver”);
Class.forName(“com.mysql.jdbc.Driver")
Class.forName ("oracle.jdbc.driver.OracleDriver");
Establishing a connection
To establish a connection with the database, use the getConnection method of the DriverManager class.
This method returns a Connection object.

Syntax: con = DriverManager.getConnection(“url”, “user”, “password”);


Connection con = DriverManager.getConnection (“jdbc:postgresql:TestDB”, “postgres”, “”);
• The DriverManager class is responsible for keeping track of all the JDBC drivers that are
available on a system.
• First task of a JDBC program is to load an appropriate driver for the type of database being used.

/*Sample Program : program to establish connection with mydb database in postgresql*/


import java.sql.*;
import java.io.*;
class JDBCDemo
{
public static void main(String[] args) throws SQLException
{
Connection con= null;
try
{
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql:mydb","postgres","SSK");
if(con==null)
System.out.println("Connection failed ");
else
System.out.println("Connection established successfully.. ");
}
Catch(Exception e)
{
System.out.println(e);
}
}
}

Executing Queries
To execute an SQL query, you have to use one of the following classes :
 Statement
 PreparedStatement
 CallableStatement

Statement Object:
 Creating a Statement Object
Execute the createStatement() method on the Connection object
 returns a Statement object EX: Statement s = c.createStatement();
 createStatement establishes a framework for executing queries
 afterwards, run methods on the Statement object to execute an SQL statement
 Methods of the Statement Class
 Methods of the Statement class require a string parameter containing the SQL statement
 executeQuery()
 requires a String argument (a SELECT statement)
 returns a ResultSet object representing the table returned
 DQL queries are generally run using executeQuery(); a collection of tuples is returned
 executeUpdate()
 requires a String argument(an INSERT, UPDATE, or DELETE statement)
 returns an int (row count, in most cases)
 DML queries are generally run using executeUpdate(); the return value represents the
number of rows affected
 execute()
 execute can return either, but is usually used when there is no data to return
 DDL and DCL queries are generally run using execute()

ResultSetTheResultSet Interface
 A cursor that iterates through a collection of tuples Forward only
 Each Statement object can have at most one active ResultSet
 A ResultSet object represents the table returned by the select statement
 Navigation/retrieval methods
 next(): moves to the next row (first row if called for the first time), returns false if no
rows remain
 getXXX() methods return the value of a field for the current row
ResulSet example
ResultSetrs;
rs = s.executeQuery(“SELECT * FROM [ORDER]”);
rs.next(); // gets the first row (use in a loop for multiple rows)
// suppose the ORDER table has an integer field
// called quantity
intmyvar = rs.getInt(“quantity”);
// if you knew that quantity is the 2nd field in the table
myvar = rs.getInt(2);

/*Sample Program1 : Sample program to display employee data (empid, empname, empsalary)*/
import java.sql.*;
import java.io.*;
class S1_JDBCDemo_Emp
{
public static void main(String[] args) throws SQLException
{
Connection con= null;
Statement stmt = null;
ResultSetrs = null;
try
{
Class.forName("org.postgresql.Driver");
System.out.println("Driver Loaded..... ");
con = DriverManager.getConnection("jdbc:postgresql:mydb","postgres","ssk");
if(con==null)
System.out.println("Connection failed…… ");
else
{
System.out.println("Connection successful....");
stmt = con.createStatement();
rs = stmt.executeQuery("Select * from employee");
while(rs.next())
{
System.out.println("EmpID = " + rs.getInt(1));
System.out.println("EmpName = " + rs.getString(2));
System.out.println("Salary = " + rs.getInt(3));
}
con.close();
}
}
catch(Exception e)
{
System.out.println("ERROR"+e);
}
}//end of main
}// end of class
PreparedStatement Object
 PreparedStatement: a Statement that specifies parameters through Java code
 The SQL statements take different forms when you specify different parameter values
 Sometimes it is more convenient or more efficient to use a PreparedStatement object for
sending SQL statements to the database.
 This special type of statement is derived from the more general interface, Statement.
 Useful when query is performed repeatedly
 Formatting of literal values is easier
 If you want to execute a Statement object many times, it will normally reduce execution time to
use a PreparedStatement object instead.
 The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right
away, where it will be compiled.
 As a result, the PreparedStatement object contains not just an SQL statement, but an
SQL statement that has been precompiled.
 This means that when the PreparedStatement is executed, the DBMS can just run the
PreparedStatement 's SQL statement without having to compile it first.
 Creating PreparedStatement Object:
PreparedStatementmyStmt;
myStmt = myCon.prepareStatement
 Set parameter values for type and position
Methods of PreparedStatement:
setInt(int, int): This method can be used to set integer value at the given parameter index.
setString(int, string): This method can be used to set string value at the given parameter index.
setFloat(int, float): This method can be used to set float value at the given parameter index.
setDouble(int, double): This method can be used to set a double value at the given parameter
index.
 Execute the Query
executeUpdate(): This method can be used to create, drop, insert, update, delete etc. It returns int
type.
executeQuery(): It returns an instance of ResultSet when a select query is executed.

/*Sample Program2 : To perform insert and delete operations on employee table


using PreparedStatement (Empid, Empname, Empsalary)
*/
import java.sql.*;
import java.io.*;
import java.util.Scanner;
class S2_JDBCDemo_Emp
{
public static void main(String[] args) throws IOException, SQLException, Exception
{
Connection con = null;
PreparedStatement ps1 = null, ps2=null;

inteid,esal; String ename;


BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql:mydb","postgres","ssk");

if(con!=null)
System.out.println("Connection successful..");

System.out.println("Enter the employee ID, employee name and employee salary to be inserted ");
eid = Integer.parseInt(br.readLine());
ename = br.readLine();
esal = Integer.parseInt(br.readLine());

ps1 = con.prepareStatement("Insert into employee values(?,?,?)");


ps1.setInt(1,eid);
ps1.setString(2,ename);
ps1.setInt(3,esal);
ps1.executeUpdate();
System.out.println("Record Inserted..... ");

System.out.println("Enter the employee ID to be deleted ");


eid = Integer.parseInt(br.readLine());
ps2 = con.prepareStatement("Delete from employee where eid = ?");
ps2.setInt(1,eid);
ps2.executeUpdate();
System.out.println("Record Deleted..... ");

con.close();
}//end of main
}// end of class
DatabaseMetaData
 DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number ofviews etc.
 methods of DatabaseMetaData interface
 public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
 public String getDriverVersion()throws SQLException: it returns the version number of the JDBC driver.
 public String getUserName()throws SQLException: it returns the username of the database.
 public String getDatabaseProductName()throws SQLException: it returns the product name of the
database.
 public String getDatabaseProductVersion()throws SQLException: it returns the product version of the
database.
 public ResultSetgetTables(String catalog, String schemaPattern, String tableNamePattern, String[]
types)throws SQLException: it returns the description of the tables of the specified catalog. The table type
can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
 EXAMPLE:
/* Write a program to display information about the database and list all the tables in the
database. (Use DatabaseMetaData).*/

import java.sql.*;
import java.io.*;
public class SetA2MetaDataDemo
{
public static void main(String args[])throws SQLException,IOException
{
Connection con=null;
Statement st=null;
ResultSetrs=null;
ResultSetMetaDatarsmd;
try
{
Class.forName("org.postgresql.Driver");
con=DriverManager.getConnection("jdbc:postgresql:mydb",
"postgres", "ssk");

DatabaseMetaDatamtdt=con.getMetaData();
System.out.println("Driver Name: "+mtdt.getDriverName());
System.out.println("Driver Version: "+mtdt.getDriverVersion());
System.out.println("UserName: "+mtdt.getUserName());
System.out.println("Database Product Name: "+mtdt.getDatabaseProductName());
System.out.println("Database Product Version: "+mtdt.getDatabaseProductVersion());
rs=mtdt.getTables(null,null,null,new String[]{"TABLE"});
System.out.println("\nList of tables :");

while(rs.next())
System.out.println(rs.getString("TABLE_NAME"));
}

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

ResultSet metadata
 The ResultSetMetaDatainterface provides information about the structure of a particular
ResultSet.
 to get metadata of a table like total number of column, column name, column type etc. ,
ResultSetMetaData interface is used
 Methods:
o public intgetColumnCount()throws SQLException : it returns the total number of columns in
the ResultSet object.
o public String getColumnName(int index)throws SQLException: it returns the column name of
the specified column index.
o public String getColumnTypeName(int index)throws SQLException: it returns the column
type name for the specified index.
o public String getTableName(int index)throws SQLException: it returns the table name for the
specified column index.
 E.g. after executing query to get a ResultSetrs:
ResultSetMetaDatarsmd = rs.getMetaData();
for(inti = 1; i<= rsmd.getColumnCount(); i++)
{
System.out.println(rsmd.getColumnName(i));
System.out.println(rsmd.getColumnTypeName(i));
}

/*Write a program to display information about all columns in the EMPLOYEE table using
ResultSetMetaData.*/

import java.sql.*;
import java.io.*;
public class SetA3ResultMetaDataDemo
{
public static void main(String args[])throws SQLException,IOException
{
Connection con=null;
Statement st=null;
ResultSetrs=null;
ResultSetMetaDatarsmd;
try
{
Class.forName("org.postgresql.Driver");
con=DriverManager.getConnection("jdbc:postgresql:mydb","postgres", "ssk");
st=con.createStatement();
rs=st.executeQuery("Select * from employee");
rsmd=rs.getMetaData();
intnoofcol=rsmd.getColumnCount();
System.out.println("No of column:"+noofcol);
System.out.println("\n\nCOLUMN INFORMATION");
for(inti=1;i<=noofcol;i++)
{
System.out.println("\n***Table Name:"+rsmd.getTableName(i) );
System.out.println("Column No:"+i);
System.out.println("Column Name:"+rsmd.getColumnName(i));
System.out.println("Column Type:"+rsmd.getColumnTypeName(i));
System.out.println("Column display size:"+rsmd.getColumnDisplaySize(i));
}
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
}
}

ResultSet Scroll Types and Concurrency: The scroll type indicates how the cursor moves in the
ResultSet. The concurrency type affects concurrent access to the resultset. The types are given in the table
below.

EX:
Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
The ResultSet interface provides methods for retrieving and manipulating the results of executed queries.
Methods Description
beforeFirst() Default position. Puts cursor before 1st row of ResultSet.
first() Puts cursor on 1st row of ResultSet.
last() Puts cursor on last row of ResultSet.
afterLast() Puts cursor after/beyond last row of ResultSet.
absolute (intpos) Puts cursor at row number position where absolute (1) is a 1st row
and absolute (-1) is last row of ResultSet.
relative (intpos) Puts cursor at row no. position relative from current position.
next() To move to the next row in ResultSet
previous() To move to the previous row in ResultSet.
void close() To close the ResultSet.
deleteRow() Deletes the current row from the ResultSet and underlying database.
getRow() Retrieves the current row number.
moveToInsertRow() Moves the cursor to the insert row.
insertRow() Inserts the contents of the insert row into the ResultSet object and
into the database.
refreshRow() Refreshes the current row with its most recent value in the database.
close() Disposes the ResultSet.
isFirst() Tests whether the cursor is at the first position.
isLast() Tests whether the cursor is at the last position.
isBeforeFirst() Tests whether the cursor is before the first position.
isAfterLast() Tests whether the cursor is after the last position.
getXXX(String columnName) Retrieves the value of the designated column in the current row as a
corresponding type in the Java programming language. XXX
represents a type: Int, String, Float, Short, Long, Time etc.
updateRow() Updates the underlying database with the new contents of the current
row of this ResultSet object.
updateXXX(intcolumnNumber, Updates the value of the designated column in the current row as a
XXX value) corresponding type in the Java programming language. XXX
represents a type: Int, String, Float, Short, Long, Time etc.

EXAMPLE:
/* Sample program to demonstrate ScrollbleResultSet on employee data (empid, empname, empsalary)*/
import java.sql.*;
import java.io.*;
import java.util.Scanner;
class ResultSetDemo
{
public static void main(String[] args) throws SQLException
{
Connection con= null;
Statement stmt = null;
ResultSetrs = null;
Scanner sc=new Scanner(System.in);
try
{
Class.forName("org.postgresql.Driver");
System.out.println("Driver Loaded..... ");
con = DriverManager.getConnection("jdbc:postgresql:mydb","postgres","ssk");
if(con==null)
System.out.println("Connection failed…… ");
else
{
System.out.println("Connection successful....");
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("Select * from employee");
while(rs.next())
{
System.out.println("EmpID = " + rs.getInt(1)+" EmpName = " + rs.getString(2)+" Salary = " + rs.getInt(3));
}
String ans="YES";
while(ans.charAt(0)!='X')
{
System.out.println("Enter F-First, P-Previous,N-Next,L-Last X-Exit:::");
ans=sc.next();
if (ans.charAt(0)=='F')
rs.first();
else if (ans.charAt(0)=='P')
rs.previous();
if (ans.charAt(0)=='N')
rs.next();
if (ans.charAt(0)=='L')
rs.last();
System.out.println("EmpID = " + rs.getInt(1)+" EmpName = " + rs.getString(2)+" Salary = " + rs.getInt(3));
}

rs.close();
con.close();
}
}
catch(Exception e)
{
System.out.println("ERROR"+e);
}
}//end of main
}// end of class

Transaction Management in JDBC


 In JDBC, Connection interface provides methods to manage transaction.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is
committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.

 Turn off the auto-commit using the setAutoCommit() method as −


//Setting the auto commit false
// Set the auto commit false.
// This will execute all SQL statements as individual transactions
con.setAutoCommit(false);
 The commit() method of the Connection interface saves all the modifications made since the
last commit. Commit the transaction using the commit() method as −
con.commit();
 A rollback operation undoes all the changes done by the current transaction i.e. If you call
a rollBack() method of the Connection interface, all the modifications are reverted until the
last commit.
Con.rollback()

-------------------xxxxxxxxxxxxxx-------------

You might also like