JDBC Final Notes
JDBC Final Notes
JDBC Final Notes
3) Migration Projets
===========================
Types of applications using Java
===========================
1) Stanadlone applications
2) Web Applications ( C 2 B )
3) Distributed Applications ( B 2 B )
============================
How to deliver project to client ?
============================
Note: To run "web application" war file we need Server (Ex: Tomcat)
- Servlets
- Spring Web MVC
- form validation
- sending email
- sending OTP
- generate excel / pdf
- calculations
- JDBC
- Spring JDBC
- Hibernate
- Data JPA
====================
How to create JAR file
====================
c - means create
v - verbose
f - file
e - entrypoint
====================
How to Extract JAR file
====================
=====
Task
=====
3) After jar is created then delete all .java & .class files
4) Create Demo.java class with main ( ) method. Create Objects for User & Student
and print hashCode of both objects.
============================================
What is the difference between PATH & CLASSPATH ?
============================================
-> PATH is used to locate where our java s/w got installed
-> CLASSPATH is used locate where our .class files / jar files are available
Note: If we set PATH & CLASSPATH in command prompt then they are temporary. If we
close CMD then we will loose them.
============
What is API ?
============
=> JSE API contains set of classes & interfaces which are used to develop
Standalone applications
=> JEE API contains set of classes & interfaces which are used to develop Web
applications.
=> To understand classes, interfaces, methods available in the APIs Sun Microsystem
provided documentation for us.
URL : https://docs.oracle.com/javase/8/docs/api/
========================================
How to create documentation for our project ?
========================================
-> To create documentation for our project we can use below command
Note: To provide metadata of our code (class, methods, interfaces) we will use java
documentation comments
/**
*
*
*
*/
==================
What is Build Path ?
==================
-> When we want to libraries in our project then we need to add them to Build Path
Ex:
----
1) servlet library we need to develop web app using java
2) To communicate with database we need jdbc library
================
Java De-Compiler
================
-> We can download java decompiler to convert byte code to source code
URL : https://github.com/java-decompiler/jd-gui/releases/download/v1.6.6/jd-gui-
windows-1.6.6.zip
=============
Database
=============
=> Database Server software will store the data in the form of tables, rows and
columns
=> Database Client software is used to communicate with Database Server Software
SQL
DataBase client -----------------------------------> Database
Server
Note: SQL (Structured Query Language) queries will be used to communicate Database
Server
=> To communicate with Oracle DB server we can use "SQL Developer" as a client
software
=> To communicate with MySQL DB server we can use "MySQL Workbench" as a client
software
Note: SQL Developer & MySQL Workbench softwares are used to execute SQL queries
======
JDBC
======
=> Using JDBC API we can communicate with Database software using Java Program
=> JDBC API will act as mediator between Java Program and Database software
JDBC API
Java Program ----------------------------------> Database Server
=> Database Software vendors provided implementation for JDBC API. As part of JDBC
API implementation they provided Database Driver
Note: Driver is a program which knows how to connect with Database Software.
Note: We need to download that jar file and add to project build path.
=====================
JDBC API Components
=====================
---------------
Interfaces
---------------
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
RowSet
-------------
Classes
------------
DriverManager
Types
Date
-------------------
Exceptions
--------------------
SQLException
============================
Steps to develop JDBC Program
============================
4) Execute Query
====================================
Setup Database & Table in MySQL DB
===================================
BOOK_NAME VARCHAR(100),
BOOK_PRICE INT(10)
);
commit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
}
}
===============
Types Of Queries
===============
Note: The above method parameter represents query which we want to execute and
method return type represents how many rows effected in db table with given query.
Note: The above method parameter represents query which we want to execute and
method return type represents records returned by given Query.
============================
SELECT OPERATION USING JDBC
============================
=> When we execute select query using JDBC then we will get data from database in
the form of ResultSet object
=> ResultSet Object will maintain a Cursor which will point to current row.
Note: Intially ResultSet cursor will point before first row. We need to move the
cursor to next position by calling next ( ) method.
Syntax : boolean next ( )
-> When record is present next ( ) method will return true otherwise it will return
false.
private static final String SELECT_SQL = "SELECT * FROM BOOKS WHERE BOOK_ID =
1002";
Class.forName("com.mysql.cj.jdbc.Driver");
ResultSet rs = stmt.executeQuery(SELECT_SQL);
if (rs.next()) {
int bookid = rs.getInt("BOOK_ID");
String name = rs.getString("BOOK_NAME");
double price = rs.getDouble("BOOK_PRICE");
System.out.println(bookid);
System.out.println(name);
System.out.println(price);
} else {
System.out.println("No Records Found");
}
con.close();
}
}
Requirement : Write a java program to retrieve all the records from the database
table and display on the console.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(DB_URL, DB_UNAME, DB_PWD);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SELECT_SQL);
while (rs.next()) {
System.out.println(rs.getInt("BOOK_ID"));
System.out.println(rs.getString("BOOK_NAME"));
System.out.println(rs.getDouble("BOOK_PRICE"));
}
con.close();
}
}
Note : By Default ResultSet cursor will move in forward direction. Based on the
Requirement we can make it as Bi Directional.
===========
Assignment
===========
Note: For Registration and Login read the data from keyboard.
Note: We should not insert user record with duplicate email. If any user trying to
register with duplicate email application should show error message.
==============
ResultSet Types
==============
1) TYPE_FORWARD_ONLY ( by default )
2) TYPE_SCROLL_INSENSITIVE
3) TYPE_SCROLL_SENSITIVE
1) CONCUR_READ_ONLY
2) CONCUR_UPDATABLE
ResultSet rs = stmt.executeQuery(SELECT_SQL);
rs.absolute(2);
rs.updateDouble(3, 8500.00);
rs.updateRow();
========================================================
package in.ashokit;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
Class.forName("com.mysql.cj.jdbc.Driver");
int getInt (int index ) : To get current row column data based on column index
int getInt (String columnName ) : To get current row column data based on column
index
==================
Prepared Statement
==================
=> Postional Parameters are used to supply dynamic values to Query in the Run time.
=> When we want to execute same query multiple times with different values then it
is highly recommended to use PreparedStatement.
Query Without Positional Parameters : INSERT INTO BOOKS VALUES (101, "JAVA",
5000);
"select * from users where uname = ' " + name +" and pwd ' = " + pwd + " ' ";
name : ashok--
pwd: 123
=================================================================================
Assignment : Develop JDBC application to retrieve books which are having price less
than given price.
=> Ask user to enter the price in keyboard, if user entered the price then we have
to fetch books which are having price less than user given price and display to
console
=> If user don't enter price then fetch all books and display to console
=================================================================================
package in.ashokit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1) + "--" + rs.getString(2) + "--" +
rs.getDouble(3));
}
con.close();
==============================================================================
=================================================================================
WORK_LOCATION : HYD
EMP_DEPT : HR
EMP_GENDER : Male
INSERT INTO EMPLOYEE VALUES (1, 'John', 15000.00, 'Admin', 'Male', 'Hyd');
INSERT INTO EMPLOYEE VALUES (2, 'Smith', 16000.00, 'HR', 'Male', 'Delhi');
INSERT INTO EMPLOYEE VALUES (3, 'Anil', 7000.00, 'Security', 'Male', 'Hyd');
INSERT INTO EMPLOYEE VALUES (4, 'Rose', 12000.00, 'HR', 'FeMale', 'Hyd');
INSERT INTO EMPLOYEE VALUES (5, 'Cathy', 16000.00, 'Sales', 'FeMale', 'Delhi');
=========================================================
package in.ashokit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
int index = 1;
while(rs.next()) {
System.out.println(rs.getInt(1) + "--"
+rs.getString(2)+"--"+rs.getInt(3)+"--"+
rs.getString(4)+"--"+rs.getString(5)+
"--"+rs.getString(6));
}
con.close();
}
}
===================================================================
package in.ashokit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
pstmt.executeUpdate();
System.out.println("Update completed....");
con.close();
}
}
=============
Requirement :
=============
Read Hike Percentage for Each Deparment from Keyboard and then update salary with
given percentage.
=================================================================
========================
syntax to create Procedure
========================
CREARE PROCEDURE <PROCEDURE-NAME> ( params.... )
BEGIN
// SQL STATEMENTS
END ;
DELIMITER $$
CREATE PROCEDURE getBooksData ( )
BEGIN
SELECT * FROM BOOKS;
END $$
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
ResultSet rs = cstmt.executeQuery();
while(rs.next()) {
System.out.println(rs.getInt(1) +
"-"+rs.getString(2)+"-"+rs.getDouble(3));
}
con.close();
}
}
===================== PROCEDURE WITH IN PARAMETER ==================
DELIMITER $$
CREATE PROCEDURE getBookById ( IN BID INT )
BEGIN
SELECT * FROM BOOKS WHERE BOOK_ID=BID;
END $$
=====================================================================
package in.ashokit;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Scanner;
ResultSet rs = cstmt.executeQuery();
while(rs.next()) {
System.out.println(rs.getInt(1) +
"-"+rs.getString(2)+"-"+rs.getDouble(3));
}
con.close();
}
}
BEGIN
SELECT BOOK_NAME as bname from BOOKS where BOOK_PRICE <= bprice ;
END $$
===================================================================================
=======
package in.ashokit;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.Scanner;
ResultSet rs = cstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
con.close();
}
}
================================================================================
1) Insert Image into database table
2) JDBC program to execute SQL query with IN clause (worklocation : 'Hyd' and
'Pune' )
01-Jan-2022
31-Dec-2022
===================================================================================
1) What is Class Path ?
2) How to set Class Path ?
3) What is JAR ?
4) What is API ?
5) What is JDBC ?
6) JDBC Driver
7) JDBC Connection
8) Statement ( SELECT * NON-SELECT QUERIES )
9) PreparedStatement ( SELECT * NON-SELECT QUERIES with Positional Parameters )
10) CallableStatement ( Procedures - IN & OUT Params )
11) Result Set
12) ResultSet Types (Sensitive, Insensitive ResultSet, READ-ONLY, CONCUR-UPDATABLE)
===================================================================================
====================
JDBC Batch Operations
====================
=> When we want to perform Bulk Operations in Database then we can use JDBC Batch
Operations concept.
con.close();
System.out.println("Execution Completed...");
}
}
==================================================================================
Assignment-2 : Read Employee & Emp Address Data from keyboard and insert into DB
table.
Note: Employee data should be inserted into EMP table and ADDRESS data should be
inserted into EMP_ADDRESS table.
EMP_ID INT,
EMP_NAME VARCHAR(100).
EMP_SALARY INT
======================
Transactions in JDBC
=======================
A - Atomocity
C - Consistency
I - Isolation
D - Durability
Note: When we are performing NON-SELECT OPERATIONS (insert / update/ delete) with
Database then Transaction is mandatory.
=> When we are performing multiple operations in single transaction then either all
operations should be success or none of the operation should be success.
=> In JDBC, transaction will be committed by default for every non select query
execution because by default Transaction Auto Commit is true.
con.setAutoCommit ( false ) ;
Note: When Auto Commit is false, we need to commit the transaction programmatically
to save our operation in database.
con.setAutoCommit (false);
try{
// logic to execute queries
con.commit ( );
} catch(Exception e){
con.rollback ( ) ;
}
===========
Tx - Example
============
package in.ashokit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
con.setAutoCommit(false);
try {
PreparedStatement pstmt = con.prepareStatement(EMP_INSERT);
pstmt.setInt(1, 101);
pstmt.setString(2, "John");
pstmt.setDouble(3, 1000.00);
pstmt.executeUpdate();
pstmt = con.prepareStatement(EMP_ADDR_INSERT);
pstmt.setString(1, "Hyd");
pstmt.setString(2, "TG");
pstmt.setString(3, "India");
pstmt.setInt(4, 101);
pstmt.executeUpdate();
con.commit();
System.out.println("Records Inserted...");
} catch (Exception e) {
System.out.println("Transcation Rolled Back....");
con.rollback();
}
con.close();
}
}
===================================================================================
==
Requirement : Develop JDBC application to read EMP_ID from Keyboard and then
retrieve emp data along with address based on given emp_id from Database table.
===================================================================================
==
pstmt.setInt(1, 101);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));
System.out.println(rs.getString(6));
}
con.close();
}
}
===================
Connection Pooling
===================
=> Connection Pooling is the process of getting fixed no.of connections from
database and store them into a pool for re-usability.
=> If we don't use Connection Pooling concept then our project will run into
Connections Exhausted Problem (No connections available to communicate with db)
Note: With the connection pooling we can improve performance of the application.
===========================
How to setup Connection Pool
==========================
===============================================
Steps to develop JDBC app with Hikari Connection Pool
===============================================
a) Hikar-CP.jar
b) SLF4J-api.jar
c) mysql-connector.java
package in.ashokit;
import java.sql.Connection;
import java.sql.Statement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
config.setJdbcUrl(DB_URL);
config.setUsername(DB_UNAME);
config.setPassword(DB_PWD);
config.setMaximumPoolSize(20);
config.setMinimumIdle(5);
stmt.executeUpdate(sql);
System.out.println("RECORD INSERTED.....");
con.close();
}
}
===============================
Working with Properties files in Java
===============================
-> As of now in JDBC programs we have declared Database properties which is not at
all recommended because if database properties are modified then we need to modify
our java programs also.
Note : Every database will have different credentials so when we want to change the
database then we have to change our java programs which is not a good practise.
-> We need to seperate our Java programs with Database Properties using properties
file
-> Properties file is used to configure properties in the form of key-value pair
Note: file name can be anything but extension should be .properties only
-> To work with properties files we have "java.util.Properties" class. Using this
class we can store the data in properties file and we can get data from Properties
file.
load (InputStream is) --> To load all properties into Properties object
setProperty(String key, String value ) ---> To set new property with key-value pair
=> Connection pool should be created only one time when the project starts... and
we need to re-use connections from pool for our db operations.
package in.ashokit;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
static {
try {
config.setJdbcUrl(url);
config.setUsername(uname);
config.setPassword(pwd);
config.setMaximumPoolSize(Integer.parseInt(poolSize));
} catch (Exception e) {
e.printStackTrace();
}
}
package in.ashokit;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
while (rs.next()) {
System.out.println(rs.getInt(1) + "--" + rs.getString(2) + "--" +
rs.getDouble(3));
}
rs.close();
stmt.close();
con.close();
}
==============================================================
package in.ashokit;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
pstmt.setInt(1, 101);
pstmt.setBlob(2, fis);
pstmt.close();
con.close();
package in.ashokit;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
if (rs.next()) {
System.out.println(rs.getInt(1));
byte[] stream = rs.getBytes(2);
rowSet.setUrl("jdbc:mysql://localhost:3306/advjdb");
rowSet.setUsername("ashokit");
rowSet.setPassword("AshokIT@123");
rowSet.execute();
while (rowSet.next()) {
System.out.print(rowSet.getInt(1) + "\t");
System.out.print(rowSet.getString(2) + "\t");
System.out.println(rowSet.getInt(3));
}
rowSet.close();
}
}
============================================================================
=====================
Types of JDBC Drivers
=====================
a) Type-1 Driver
b) Type-2 Driver
c) Type -3 Driver
d) Type-4 Driver
Note: Type-1, Type-2, Type-3 drivers are outdated, we are using Type-4 driver.