4. JDBC Final Notes
4. 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)
========================
Java Project Architecture
=========================
- 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 run JAR file
====================
====================
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.
-> TO set them permanently we need to use Environment Variables.
============
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.
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
/**
*
*
*
*/
==================
What is 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
SQL
DataBase client ----------------------------------->
Database Server
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
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
===============
============================
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.
-> When record is present next ( ) method will return true otherwise it
will return false.
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();
}
}
===========
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");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(SELECT_SQL);
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.
"select * from users where uname = ' " + name +" and pwd ' = " + pwd +
" ' ";
name : ashok--
pwd: 123
=> 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;
PreparedStatement pstmt =
con.prepareStatement(sql.toString());
if (price > 0) {
pstmt.setDouble(1, price);
}
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
=========================================================
package in.ashokit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
PreparedStatement pstmt =
con.prepareStatement(sql.toString());
int index = 1;
ResultSet rs = pstmt.executeQuery();
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;
PreparedStatement pstmt =
con.prepareStatement(UPDATE_SAL_SQL);
pstmt.setDouble(1, hike);
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
========================
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;
Connection con =
DriverManager.getConnection(DB_URL,DB_UNAME,DB_PWD);
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 $$
// call the procedure in workbench
=====================================================================
package in.ashokit;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Scanner;
Connection con =
DriverManager.getConnection(DB_URL,DB_UNAME,DB_PWD);
ResultSet rs = cstmt.executeQuery();
while(rs.next()) {
System.out.println(rs.getInt(1) + "-"+rs.getString(2)+"-
"+rs.getDouble(3));
}
con.close();
}
}
DELIMITER $$
CREATE PROCEDURE getBookNameByPrice
(
IN bprice INT,
OUT bname VARCHAR(100)
)
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
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.
Ex: insert 100 records into table at a time
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
con.setAutoCommit ( false ) ;
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
===================
===========================
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
===============================
-> We need to seperate our Java programs with Database Properties using
properties file
Note: file name can be anything but extension should be .properties only
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);
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);
JdbcRowSet rowSet =
RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:mysql://localhost:3306/advjdb");
rowSet.setUsername("ashokit");
rowSet.setPassword("AshokIT@123");
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.