Unit 2_JDBC
Unit 2_JDBC
Unit 2_JDBC
Chapter 2
By: B.U.Gadhia
Introduction
•JDBC (Java Database connectivity) is nothing but a Java API (Application
programming Interface)
•The function of this Java API is to document a standard framework for dealing with
data which may be tabular and generally relational data.
•The role of JDBC is just to act like a wrapper to let us feed SQL requests to the server
•It would not be desirable for a literal translation of the ODBC API into a Java API. Example, Java
has no pointer and ODBC makes copious use of them.
•ODBC is hard to learn. It is seen that in ODBC, simple and advanced features are mixed together,
and it has complex option for simple queries. On the other hand, JDBC was designed to keep
simple things simpler, while allowing more advanced capabilities as and when required
•The ODBC driver manager and drives must be manually installed on every client machine, when
ODBC is used. Although JDBC driver is written completely in Java, JDBC code is automatically
installable, portable and secure on all Java platforms from network computer to mainframes
JDBC Component
Driver Manager It load the database drivers and manages connection between the
application and the driver
Driver It translates API calls into operation for a specific data source
MetaData It gives information about returned data, the database and the driver
ResultSet It is the logical set of columns and rows of data returned by executing
a statement
General Architecture
5
6
Exploring JDBC Drivers
•Type-1 Driver
•Type-2 Driver
•Type-3 Driver
•Tpe-4 Driver
Type-1 Driver
Type-2 Driver
Type-3 Driver
Type-4 Driver
Basic steps to use
a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
12
1. Establish a connection
•import java.sql.*;
•Load the vendor specific driver
–Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
–Connection con =
DriverManager.getConnection("jdbc:odbc:CITY_MASTER");
•What do you think this statement does?
•Establishes connection to database by obtaining
•a Connection object
13
2. Create JDBC statement(s)
•Statement stmt = con.createStatement() ;
•Creates a Statement object for sending SQL statements to the
database
14
Executing SQL Statements
•String Query= "select * from City_Master";
15
Get ResultSet
String Query= "select * from City_Master";
ResultSet rs = Stmt.executeQuery(Query);
//What does this statement do?
while (rs.next()) {
16
Close connection
•stmt.close();
•con.close();
17
Step-1 Create new Blank database
Step-2 Make Table in database
Step-3
•Go to Control panel-> Administrative tools
Step-4 Select MS Access Database
Step-5 Select MS Access Driver
Step-6 Choose directories and
select database
Step-7
Create Database
Change Database
Create Table and insert Records
Display Table
C:\Users\Admin\.m2\repository\mysql\mysql-connector-
java\5.1.22\mysql-connector-java-5.1.22.jar
JDBC Example(Linux-MySql)
import java.sql.*;
public class Mysqldemo1
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver is loaded");
Connection c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master",
"root","123456");
System.out.println("Connection created");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("select * from city");
System.out.println("ID\t CITY_CODE\t City_NAME\t CITY_STATE");
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3 )+"\t“
+rs.getString(4));
}
catch(Exception e)
{
System.out.println("Exception : " +e);
}
}
}
OUTPUT
JDBC Program(Windows - ODBC)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
Database Access
Java.sql.Statement Executes Sql statements
Java.sql.PreparedStatement Executes parameterized sql statements
Database Metadata
Java.sql.DatabaseMetadata Obtains database features
Java.sql.ParameterMetadata
Java.sql.Resultsetmetadata Provides methods to access metadata of
result set
Exceptions and Warnings
Java.sql.BatchUpdateExceptions Updates Batches
import java.sql.*;
public class Mysqldemo1
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver is loaded");
Connection c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","123456");
System.out.println("Connection created");
Statement s = c.createStatement();
String Query="insert into city values(5,011,'Mumbai','Maharashra')";
int count=s.executeUpdate(Query);
System.out.println("No. of Recodrds inserted:"+count);
}
catch(Exception e)
{ System.out.println("Exception : " +e);
}
}
}
Do your self
•String query = " SELECT * FROM CITY WHERE
State='"+state+"'";
Executing Query
•To execute a query, call an execute method
from Statement such as the following:
• execute: Returns true if the first object that the query returns is a ResultSet
object. Use this method if the query could return one or moreResultSet
objects. Retrieve the ResultSet objects returned from the query by repeatedly
calling Statement.getResutSet.
•executeQuery: Returns one ResultSet object.
•executeUpdate: Returns an integer representing the number of rows
affected by the SQL statement. Use this method if you are using
INSERT,DELETE, or UPDATE SQL statements.
Demo of Execute Query
String state=”Gujarat”;
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
stmt.executeUpdate(sql);
stmt.close();
import java.sql.*;
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE city SET CITY_CODE = 30 WHERE CITY_NAME='SURAT'";
stmt.executeUpdate(sql);
sql = "SELECT ID,CITY_CODE, CITY_NAME,CITY_STATE from city";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master",
"root","123456");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCU
R_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from city");
rs.relative(3);
rs.last();
con.close();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
Delete Query
import java.sql.SQLException;
import java.sql.Statement;
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Creating statement...");
stmt = conn.createStatement();
while(rs.next()){
int id = rs.getInt("ID");
int age = rs.getInt("CITY_CODE");
String first = rs.getString("CITY_NAME");
String last = rs.getString("CITY_STATE");
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
System.out.println("Goodbye!");
}
}
Delete Output
Difference between Statement & Prepared Statement
•There are four steps for the execution of query :
Query is parsed,
Query is compile,
Query is optimized and
Query is executed.
In case of statement interface these four steps are performed ,each time
when query is submitted for execution.
do{
System.out.println("Enter Id:");
int id=Integer.parseInt(br.readLine());
System.out.println("Enter Code:");
int code=Integer.parseInt(br.readLine());
System.out.println("Enter Name");
String city_name=br.readLine();
System.out.println("Enter State");
String city_state=br.readLine();
ps.setInt(1,id);
ps.setInt(2,code);
ps.setString(3,city_name);
ps.setString(4,city_state);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
}while(true);
con.close();
}
}
Do by yourself
Write a program to update city name to
‘Ahmedabad’ where City Code=‘079’
using Prepared Statement.
//STEP 1. Import required packages
import java.sql.*;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","123456");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
ResultSet rs = stmt.executeQuery(sql);
int id = rs.getInt("id");
int city_code = rs.getInt("City_code");
String city_name = rs.getString("city_name"); OR
String city_state = rs.getString("city_state");
//Display values
System.out.print(" ID : "+rs.getString(1));
System.out.print(" CITY_CODE: "+rs.getString(2));
System.out.print(" CITY_NAME "+rs.getString(3));
System.out.println(" CITY_STATE: "+rs.getString(4));
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}//end main
}//end JDBCExample
Definition: W. A. P To Display the information of of City Baroda,
Ahmedabad, Mumbai using “PreparedStatement Interface”.
import java.sql.*;
try {
Class.forName(driver);
con = DriverManager.getConnection(connection);
String sql =
"select * from City_Master where CITY_NAME " + "in(?,?,?)";
pst = con.prepareStatement(sql);
pst.setString(1, "Baroda");
pst.setString(2, "Ahmedabad");
pst.setString(3, "Mumbai");
rs = pst.executeQuery();
System.out.println("EmployeeID\tFirstName");
while (rs.next())
{
System.out.print(" "+rs.getString(1));
System.out.print("\t\t"+rs.getString(2));
System.out.println("\t\t"+rs.getString(3));
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
CALLABLE
STATEMENT
Create Stored Procedure
import java.sql.*;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
String sql = "{call empproc2 (?, ?)}";
stmt = conn.prepareCall(sql);
stmt.registerOutParameter(2,Types.INTEGER);
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}//end main
}//end JDBCExample
Table Creation
create table Emp
(
varchar(10) primary key,
name varchar(40) null,
city varchar(20),
salary int
);
insert into Emp values('a001','Ram Kumar','Noida',10000);
Using Callable Statement
CREATE PROCEDURE proc1()
BEGIN
SELECT * from Employee
FROM emp;
END; //
try {
clmt = con.prepareCall("{call proc2}");
ResultSet res = clmt.executeQuery();
while (res.next()) {
System.out.println(res.getString(1) + " " + res.getString(2)
+ " " + res.getString(3) + " " + res.getString(4));
}
} catch (Exception e) {
e.printStackTrace();
}
Using Callable Statement (IN Parameter)
CREATE PROCEDURE proc3(IN code1 varchar(10),IN name1 varchar(10))
BEGIN
insert into emp(code,name) values(code1,name1);
END; //
try {
clmt = con.prepareCall("{call proc3(?,?)}");
clmt.setString(1, code);
clmt.setString(2, name);
int i = clmt.executeUpdate();
if (i != 0)
System.out.println("Inserted successfully");
else
System.out.println("Not Inserted");
} catch (Exception e) {
}
Using Callable Statement (IN & Out Parameter)
CREATE PROCEDURE proc4(IN code1 varchar(10), OUT name1 varchar(10))
BEGIN
SELECT name from emp where code=code1
INTO name1;
END; //
try {
clmt = con.prepareCall("{call proc4(?,?)}");
clmt.setString(1, code);
clmt.registerOutParameter(2, Types.VARCHAR);
clmt.execute();
System.out.println(clmt.getString(2));
}
catch (Exception e) {
}
Store Image in to Database
(BLOB DataType)
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","
123456");
FileInputStream fin=new
FileInputStream("/Home/NetBeansProjects/JavaApplication1/src/javaapplication1/pr
epared.png");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();}
}
}
Methods of BLOB Interface
Methods Description
ps.setInt(1,Integer.parseInt(s[0]));
File f=new File(s[1]);
FileReader fr= new FileReader(f);
ps.setCharacterStream(2,fr, (int)f.length());
int i=ps.executeUpdate();
System.out.println("Record inserted successfully , count : "+i);
con.close();
}//main
}//class
import java.sql.*;
Describing Array Data type
import java.util.*;
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","");
ps.setInt(1, 7934);
ps.setString(2, "12345A134");
String s1[] = {"v1", "v2", "v3", "v4", "v5"};
String visaNumbers = String.join(",", s1); // Convert array to comma-separated string
ps.setString(3, visaNumbers);
int i = ps.executeUpdate();
System.out.println("Row Inserted, count : " + i);
con.close();
}
}
Database Metadata
import java.sql.*;
class dbmd{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","123456");
DatabaseMetaData dbmd=con.getMetaData();
con.close();
}
}
Output of Database Metadata
import java.sql.*;
class Rsmd ResultSet Metadata
{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","
123456");
ResultSetMetaData rsmd=rs.getMetaData();
con.close();
Concurrency of ResultSet:
–Default: CONCUR_READ_ONLY.
oResultSet.CONCUR_READ_ONLY
oResultSet.CONCUR_UPDATABLE
Method Description
public boolean first() throws SQLException
// Create a statement
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
if (resultSet.first()) { displayCityInfo(resultSet); }
resultSet.last();
displayCityInfo(resultSet);
resultSet.absolute(3);
displayCityInfo(resultSet);
resultSet.relative(1);
displayCityInfo(resultSet);
resultSet.previous();
displayCityInfo(resultSet);
resultSet.next();
displayCityInfo(resultSet);
// Close connection
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
System.out.println("City ID: " + cityId + ", City Name: " + cityName + ", City_State : " + city_state);
}
}
Methods & Description :
• public void updateRow()
• Updates the current row by updating the corresponding row in the database.
• public void deleteRow()
• Deletes the current row from the database
• public void refreshRow()
• Refreshes the data in the result set to reflect any recent changes in the database.
• public void cancelRowUpdates()
• Cancels any updates made on the current row.
• public void insertRow()
• Inserts a row into the database. This method can only be invoked when the cursor
is pointing to the insert row.
import java.sql.*;
public class jdbcConn
{
public static void main(String[] args) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver
Connection con = DriverManager.getConnection("jdbc:odbc:CITY_MASTER");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE) ;
rs.last();
System.out.println("No of rows in table="+rs.getRow());
rs.moveToInsertRow();
rs.updateInt("ID", 9);
rs.updateString("City_Code","055");
rs.updateString("City_Name", "SURAT");
rs.updateString("City_Name", "SURAT");
rs.updateString("City_State", "GUJARAT");
rs.insertRow();
System.out.println("Row added");
}
}
Output
Batch Updates
•Send Multiple updates
•Ex.
Statement st=con.createStatement();
System.out.println("Creating statement...");
stmt = conn.createStatement();
}
catch(SQLException se){
se.printStackTrace();
}
}//end main
}//end JDBCExample
Transactions
JDBC allows SQL statements to be grouped together into a single transaction.
•con.setAutoCommit(false);
•con.rollback();
•con.commit();
•con.setAutoCommit(true);
import java.sql.*;
public class JdbcAutocommit
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver
Connection con = DriverManager.getConnection("jdbc:odbc:Cust_MASTER");
con.setAutoCommit(false);
Statement st = con.createStatement();
String sql = “Update customer set cust_name=“ABC ” where cust_id=123";
rs = st.executeQuery(sql);
con.Commit();
catch (Exception e)
{ System.out.println(e); } } }
try{
conn.setAutoCommit(false);
String SQL = "INSERT INTO Employees " + "VALUES (105, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
String SQL = "INSERT IN Employees " + "VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
conn.commit();
}
catch(SQLException se)
{
conn.rollback();
}
import java.sql.*; Demo of Transaction Management
import java.util.*;
import java.io.*;
String srcaccno=“1";
String destaccno="2";
ps.setInt(1,-500);
ps.setString(2,srcaccno);
int j=ps.executeUpdate();