Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

WEB TECHNOLOGY

KCS-602

by

Dr. Seema Maitrey


M.Tech(CE), Ph.D(CSE)

Department of Computer Science &


Engineering
Contents
❑ Java Database Connectivity (JDBC)

❑ Merging Data from Multiple Tables

❑ Joining, Manipulating, Databases with JDBC

❑ Prepared Statements, Processing Stored Procedures

❑ Transaction

❑ MetaData
JDBC (Java Database Connectivity)
• It’s a java API to connect & execute query with DB
• JDBC API uses JDBC drivers to connect with DB.
Why use JDBC
• Before JDBC, ODBC API was the database
API to connect and execute query with DB.
• But, ODBC API uses ODBC driver which is
written in C language (i.e. platform
dependent and unsecured).

That is why Java has defined its own API


(JDBC API) that uses JDBC drivers (written in
Java language).
JDBC Driver
It is a software component that enables java
application to interact with the DB.

There are 4 types of JDBC drivers:


• Type-1 driver or JDBC-ODBC bridge driver
• Type-2 driver or Native-API driver (partially java
driver)
• Type-3 driver or Network Protocol driver (fully
java driver)
• Type-4 driver or Thin driver (fully java driver)
1) Type-1: JDBC-ODBC bridge driver

• uses ODBC driver to connect to DB.


• It converts JDBC method calls into the
ODBC function calls.
• It is also called Universal driver because it
can be used to connect to any of the DBs.
• This is now discouraged because of thin
driver.
Cont..

Advantages:
• easy to use.
• can be easily connected to any DB.

Disadvantages:
• Performance degraded because JDBC method
call is converted into the ODBC function calls.

• The ODBC driver needs to be installed on the


client machine.
2) Type-2: Native-API driver

• It uses the client-side libraries of


the DB.
• The driver converts JDBC
method calls into native calls of
the DB API.

• It is not written entirely in java.


Cont..

Advantage:
• performance upgraded than JDBC-ODBC
bridge driver.

Disadvantage:
• The Native driver needs to be installed on
the each client machine.

• The Vendor client library needs to be


installed on client machine.
3) Type-3: Network Protocol driver

• It uses middleware (application server)


that converts JDBC calls directly or
indirectly into vendor-specific DB
protocol.

• It is fully written in java.


Cont…
Advantage:
• No client side library is required because of
application server that can perform many tasks
like auditing, load balancing, logging etc.

Disadvantages:
• Network support is required on client machine.
• Requires DB-specific coding to be done in middle
tier.
• Maintenance of Network Protocol driver becomes
costly because it requires DB-specific coding to be
done in the middle tier.
4) Type-4: Thin driver

• It converts JDBC calls directly into


the vendor-specific DB protocol.
That is why it is known as thin driver.
• It is fully written in Java language.
• Currently, we will use “Type-4”.
Cont…
Advantage:
• Better performance than all other drivers.
• No software is required at client side or
server side.

Disadvantage:
• Drivers depends on the Database.
5 Steps to connect to the DB in java
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1) Register the driver class
• The forName() method of class Class is used to
register the driver class. It dynamically load the
driver class.

Example to register the OracleDriver class=➔>>

Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
• The getConnection() method of
DriverManager class is used to establish
connection with the DB.

Ex: to establish connection with the Oracle DB

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","pa
ssword");
3) Create the Statement object
• The createStatement() method of Connection
interface is used to create statement.
• The object of statement is responsible to execute
SQL & return the results by using the ResultSet
object.

Ex: to create the statement object:


Statement stmt=con.createStatement();
4) Execute the query
• The executeQuery() method of Statement interface is
used to execute queries to the DB. This method returns
the object of ResultSet that can be used to get all the
records of a table.

Ex: to execute query


ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
• By closing connection object, statement
& ResultSet will be closed automatically.
• The close() method of Connection
interface is used to close the connection.

Ex: to close connection


con.close();
Example to connect to the MySql DB
Along with 5 steps-
Import the packages(import java.sql.* ) : contain the JDBC classes
needed for DB programming.
other information is as :
• Driver class: com.mysql.jdbc.Driver.
• Connection URL: jdbc:mysql://localhost:3306/kiet
where
➢jdbc is the API,
➢mysql is the DB,
➢localhost is the server name on which mysql is
running, we may also use IP address,
➢3306 is the port number and kiet is the DB name.
• Username: The default username for the mysql DB is root.
• Password: It is given by user during installation of mysql DB
Cont..
• First create a table in the mysql DB, but before creating
table, we need to create DB first.

–create database kiet;


–use kiet
–create table student(sid int(10),sname
varchar(20),email varchar);
Connect Java Application with mysql DB
Here, kiet is DB name, root is the username and password is empty.
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/kiet","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
con.close();
}catch(Exception e){ System.out.println(e);}
} } The above example will fetch all the records of student table.
To connect java application with mysql db, mysqlconnector.jar file is required to be loaded.
Two ways to load the jar file:
Set classpath:
1) Download the mysqlconnector.jar file. Go to jre/lib/ext folder and
paste the jar file here.
2) Set classpath: There are two ways to set the classpath:
temporary and permanent
How to set the temporary classpath:

open command prompt and write:


C:>set classpath=C:\Program Files\Java\jre1.8.0_271\lib\ext\mysql-
connector.jar;

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name
write classpath and in variable value paste the path to the
mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\Program Files\Java\jre1.8.0_271\lib\ext\mysql-connector.jar;
Common piece of code in all programs of JDBC
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/k
iet","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
A) To display all records from a DB table:
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/kie
","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
con.close();
}catch(Exception e)
{
System.out.println(e);}
}}
B) To insert record into student table(using statement)
….
….
Statement st = conn.createStatement();
String str="insert into student(sid,sname) values(103,'Kanak')";
int r=st.executeUpdate(str);
System.out.println(r+"\t Rows created successfully!!!");
System.out.println(“\n ======Display Result========“);
ResultSet rs = st.executeQuery("SELECT * from student");
// Retrieve the results
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}//while
conn.close();
}catch(Exception e)
{ System.out.println(e);}
}}
C) To Delete record
….
….
Statement st = conn.createStatement();
String str="delete from student where sid=103 ";
int r=st.executeUpdate(str);
System.out.println(r+"\t Rows Deleted Successfully!!!");
System.out.println(“\n ======Display Result========“);
ResultSet rs = st.executeQuery("SELECT * from student");
// Retrieve the results
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}//while
conn.close();
}catch(Exception e){ System.out.println(e);}
}}
D) To Update record
Statement st = conn.createStatement();
String str="update student set sname='Abhineet' where
sid=101 ";
int r=st.executeUpdate(str);
System.out.println(r+"\t Rows Updated Successfully!!!");
ResultSet rs = st.executeQuery("SELECT * from student");
// Retrieve the results
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}//while
conn.close();
}catch(Exception e)
{ System.out.println(e);}
}}
PreparedStatement interface
• It is a subinterface of Statement.
• Used to execute parameterized query. It accepts input
parameters at runtime.
• A SQL statement is precompiled and stored in a
PreparedStatement object
• Its object is created using the prepareStatement()
method of Connection interface, as:
String query = “insert into emp values(? ,?)”;
PreparedStatement ps =
con.prepareStatement(query);
ps.setInt(1,105);
ps.setString(2,”Meenal”);
int n = ps.executeUpdate();
Use of PreparedStatement:

Improves performance:
- can be used to represent a precompiled query,
which can be executed multiple times.

Disadvantage:
It can represent only one SQL statement at a time.
Example of PreparedStatement interface that inserts the record
import java.sql.*;
public class insertPST {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/kiet","root","");
String query="insert into student values(?,?)";
PreparedStatement pst=con.prepareStatement(query);
pst.setInt(1,103);
pst.setString(2, "Bhanu");
int r=pst.executeUpdate();
System.out.println(r+"\t Rows Inserted Successfully!!!");
ResultSet rs = pst.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
}catch(Exception e) {
System.out.println(e);}
}}
Example of PreparedStatement interface that updates/deletes/retrieves the record
String query="update student set sname=? where sid=?";
PreparedStatement pst=con.prepareStatement(query);
pst.setInt(2,103);
pst.setString(1, "Bhavya");
int r=pst.executeUpdate();
System.out.println(r+"\t Rows Updated Successfully!!!");

Example of PreparedStatement interface that deletes the record


String query="delete from student where sid=?";
PreparedStatement pst=con.prepareStatement(query);
pst.setInt(1,104);
int r=pst.executeUpdate();
System.out.println(r+"\t Rows Deleted Successfully!!!");
Example of PreparedStatement interface that retrieve the records of a table
String query="select * from student";
PreparedStatement pst=con.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
}catch(Exception e) {
System.out.println(e);
}}}
CallableStatement(Interface)

- Used to call the stored procedures and functions.


For this, its object is needed.

• The object is created using the prepareCall()


method of Connection interface.

CallableStatement cs=con.prepareCall("{call
Proc_Name(?,?)}");

// calls procedure that receives 2 arguments.


Differentiate Statement, Prepared Statement and Callable Statement

Statement Prepared Statement Callable Statement

Super interface for Prepared and Callable extends Statement (sub- extends PreparedStatement (sub-
Statement interface) interface)

Used for executing simple


SQL statements like CRUD (create, Used for executing dynamic and
Used for executing stored procedures
retrieve, update and delete pre-compiled SQL statements

PreparedStatement CallableStatement
ps=con.prepareStatement cs=conn.prepareCall("{call
stmt = conn.createStatement(); ("insert into studentDiet
values(?,?,?)"); getbranch(?,?)}");

It faster because it is used for


Slower as compared to Prepared None
executing precompiled SQL
Statement
statement in java JDBC.

java.sql.Statement is suitable for executing java.sql.PreparedStatement is


DDL commands suitable for executing DML java.sql.CallableStatement is
commands – suitable for executing stored
- CREATE, drop, alter and truncate in SELECT, INSERT, UPDATE and procedure.
java JDBC. DELETE in java JDBC.
Differentiate executeQuery(), executeUpdate() and execute()

executeQuery() executeUpdate() execute()


ResultSet executeQuery int executeUpdate(String sql) Boolean execute(String sql)
(String sql) throws SQLException throws SQLException
throws SQLException

• used for reading content of • used for altering the DBs • If you dont know which
DB • Statement: DROP, INSERT, method to be used for
UPDATE, DELETE used. executing SQL statements,
this method can be used.
• The output will be in the form
of ResultSet. • Output will be in the form of • This will return a boolean.
int.
• Generally SELECT statement • This int value denotes the • TRUE indicates the result is a
is used. number of rows affected by ResultSet and FALSE indicates
the query. it has the int value which
denotes number of rows
affected by the query.

E.g.:ResultSet rs= E.g.: int i= E.g.: Boolean b=


stmt.executeQuery(query); stmt.executeUpdate(query); stmt.execute(query);
ResultSet
◼ ResultSet objects provide access to a table that is the result of a SQL query
◼ maintain a cursor pointing to the row of data
◼ this cursor initially points before the first row and is moved to the first
row by the next() method

ResultSet rs = statement.executeQuery("SELECT * from student”);


while ( rs.next( ) )
{
String name = rs.getString( "sname”);
int id = rs.getInt(sid);
System.out.println("SName: "+name+", Roll No: "+sid);
}
ResultSet navigation methods

Method Semantics
first() Moves cursor to first row
last() Moves cursor to last row
next() Moves cursor to next row
previous() Moves cursor to just before the first row
afterLast() Moves cursor to just after the last row

absolute(int) Moves cursor to a row index. If positive –


counting from the front, if negative – from the
back
relative(int) Moves cursor a relative number of rows, positive
or negative from the current position
getXXX(…) methods
◼ It take a column name or the number of the
column
◼ column numbers start at 1 & go from left to right

For example:

◼ rs.getString(“sname”):
returns the student name as a String

◼ in fact, we can get any of the SQL types with


getString(…) and it will automatically be
converted to a String
Transactions
◼ It is the propagation of one or more changes to DB
Ex: creating/updating/deleting a record from the table.

◼ It is important to control these transactions to


ensure the data integrity and to handle DB errors.
◼ Normally each SQL statement will be committed
automatically when it has completed executing
(auto commit is on)
◼ A group of statements can be committed together
by turning auto commit off, and explicitly
committing the statements ourselves
◼ This ensures that if any of the statements fail, they all
fail. We can then roll back the transaction
Transactions

Advantage of Transaction Management


• Fast performance: because DB is hit at the
time of commit.

In JDBC, Connection interface provides methods


to manage transaction.
void setAutoCommit(boolean status) It is true by default means each transaction is
committed by default.

void commit() Commits the transaction.

void rollback() Cancels the transaction.


ACID properties
It describes the transaction management well.
ACID stands for Atomicity, Consistency, isolation and durability.
• Atomicity: means either all successful or none.
• Consistency: ensures bringing DB from one consistent state to another consistent state.
• Isolation: ensures that transaction is isolated from other transaction.
• Durability: once a transaction has been committed, it will remain so, even in the event of
errors, power loss etc.
import java.sql.*;
class RollbackDemo{
public static void main(String args[]){
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/kiet","root","");
con.setAutoCommit(false); //bydeafault it is true
Statement stmt=con.createStatement();
int i=stmt.executeUpdate("insert into student values(105,’Shree')");
con.commit(); //Commit Transaction
i+=stmt.executeUpdate("insert into student values(106,’vanshika')");
System.out.println("no. of rows inserted="+i);
con.commit(); // Commit Transaction
con.rollback(); //Rollback Transaction
con.close(); }}
MetaData
◼ JDBC has facilities to get information about a
ResultSet or DB
◼ for a ResultSet, this information may include:
1. total number of column
2. column name
3. column type etc.
◼ for a DB this information may include the name of the driver, the
DB URL etc.
◼ This information about a ResultSet or DB is known as
Metadata
Following classes used as:

◼ For ResultSet(table) : ResultSetMetaData interface is useful because it


provides methods to get metadata from the ResultSet object
◼ For Database : DatabaseMetaData interface provides methods to get
meta data of a database
(1) ResultsetMetaData Interface with Example.
import java.sql.*;
public class resultsetMD {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/kiet","root","");
String query="select * from student";
Statement st=con.createStatement();
ResultSet rs = st.executeQuery(query);
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(); OUTPUT:
}catch(Exception e)
{
System.out.println(e);
}}}
(2) DatabaseMetaData Interface with Example
DatabaseMetaData interface provides methods to get meta data of a DB such as:
DB product name , DB product version , Driver name, Name of total number of tables etc.

import java.sql.*;
public class databaseMD {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/kiet","root","");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println ("getDatabaseProductName:"+dbmd.getDatabaseProductName());
System.out.println("getDatabaseProductVersion():"+dbmd.getDatabaseProductVersion());
System.out.println("getDriverName():"+dbmd.getDriverName());
System.out.println("getDriverVersion():"+dbmd.getDriverVersion());
System.out.println("getURL():"+dbmd.getURL());
System.out.println("getUserName():"+dbmd.getUserName());
con.close();
}catch(Exception e)
{
System.out.println(e);
}}}

OUTPUT:
Thank
You

You might also like