[go: up one dir, main page]

0% found this document useful (0 votes)
37 views24 pages

JDBC-1 1

Uploaded by

Ashok Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views24 pages

JDBC-1 1

Uploaded by

Ashok Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

ADVANCE JAVA TYPES OF APPLICATION

It is used to create a complete application.


→ By using Advance java we can create web application.
APPLICATION
The collection of programs is known as application.
→ We have 4 types of applications.
1. Stand Alone Application
2. Web Application
3. Mobile Application
4. Distributed Application
1.) STAND ALONE APPLICATION
→ The application which will work without internet is known as Stand
Alone Application.
→ To develop Stand Alone Application we require Core Java.
→ Stand Alone Applications are present in Client Machine (User System).
Example: Calculator, Notepad, EditPlus, Gallery, Music, Settings etc.
------------------------------------------------------------------------------------------
NOTE: Stand Alone Applications are known as Independent Applications.
2.) WEB APPLICATION
→The application which will work with internet and browser is known as
Web Application.
→ To develop Web Application we require Web Technology and Advance
Java.
→ Web Applications are not present in Client Machine.
Example: Facebook, Myntra, Flipkart, Amazon etc.
-------------------------------------------------------------------------------------------
NOTE: Browser is an application which is used to access Web Applications
by using Internet.

COMPONENTS OF WEB APPLICATIONS


→ There are two components for Web Applications
1. Front-End
2. Back-End
1. FRONTEND
→ The elements which are visible to the user is known as Front-End of an
application.
→ To develop Front-End of an application we
require Web Technologies.
2. BACKEND
→ The elements which are not visible to the user is known as Back-End of
an application.
→To develop Back-End of an application we require Java, SQL.
TYPES OF WEB APPLICATIONS
→ There are two types of Web Application
1. Static Web Application
2. Dynamic Web Application
1. Static Web Application
→ The application which contains only Front-End is known as Static Web
Application.
→ To develop Static Web Applications we have to use Web Technologies.
2. Dynamic Web Application
→ The application which contains only Front-End as well as Back-End is
known as Dynamic Web Application.
→ To develop Dynamic Web Applications we required Advance Java
(which includes Java, SQL and Web Technologies).
SERVER
→ Server is a machine which is used to store Web Application.
→ Servers are the mediator between Developer and User.
→ Developer is using the server to store the Web Applications.
→ User is using the server access Web Applications by sending Request and
Response.
3.) MOBILE APPLICATION
→ The Application which needs to download and install in Mobile is known
as Mobile Application
→ Mobile Applications are developed by using FLUTTER Technology.
→ To use mobile applications in mobile we need Operating System.
Example: Android, IOS, Linux, Java
4.) DISTRIBUTED APPLICATION
→ The applications which are interconnected is known as Distributed
Applications.
→ Distributed Applications are developed by using Cloud Technology.
Example: Google(Gmail,GMap,GDrive,GPhotos,Youtube),
Amazon(AmazonPay,Prime,Music,Shopping)
WORKING WITH ECLLIPSE
WORKSPACE Collection of Programs
PROJECT Collection of Packages
PACKAGE Collection of Classes & Interfaces PROGRAM
package demo;
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Advance Java");
}
}

OUTPUT
Welcome to Advance Java

PACKAGE CREATION
→ We can create an application in two ways based on industries.
1. Commercial Application
2. Organizational Applica

1. Commercial Application
→ The applications which can be accessed by anyone is known as
Commercial Application.
Example: Facebook, Phonepe, Gpay etc

2. Organizational Application
→ The applications which can be accessed only by authorized people is
known as Organizational Application.
Syntax to create a package
Way of an application / Company_name / Project_name
Example: 1. com.google.gmail
2. org.datavalley.ai
-------------------------------------------------------------------------------------------
NOTE: ==> ‘.’ is used to create a folder inside a folder

JAR FILE
✓ JAR file stands for “Java ARchive”.
✓ JAR files are the compressed version of Java Programs.
✓ Compressed version of files (or) folders is known as ZIP file.
✓ ZIP files are used to share large data files with one person to another
person.
✓ JAR files are the mediators between two developers.
✓ The process of sharing java programs from one developer to another
developer by converting as JAR file is known as Communication
Medium.
✓ JAR files are used to provide a security for Java Programs. Because
JAR files cannot be modifiable.
✓ JAR files are used to share Java programs from one developer to
another developer.
STEPS TO CREATE JAR FILES
1. Select the Project and Right click on the Project.
2. Select the option Export
3. In wizard or suggestion box search as ‘JAR’.
4. Select an option Java/JAR File.
5. Specify the location to save the JAR file 6. Mention the file name and
click on Save.
6. Click on Finish.

PACKAGE (FOLDERS )
Java project will contain two folders.
1. Source folder
2. Bin folder
✓ Source folder contain source file of java programs.
✓ Source files are used to Read the code.
✓ Bin folder contains class files of Java program.
✓ Class files are used to execute the code.
✓ JAR file will contain only Class files(Developer can only execute).
JAVA BUILT PATH
✓ We have to perform Java build path to make use of the JAR file which is
shared from one developer to another developer.
✓ Without performing we cannot use any type of JAR files.
STEPS TO PERFORM JAVA BUILD PATH
1. Copy the JAR file and paste it in the project.
2. Right click on the project then Select the option ‘Properties’.
3. Select the Java build path and Click on ‘Libraries’ (The option which is
present on the top of the window).
4. Select ‘Add JARs’ and choose the Jar file which is present in respective
project.
5. Click on ‘Ok’ and Click on ‘Apply and Close’

HOW TO REMOVE MODULE PATH ERROR


1. Select the Project and Click on the project
2. Go for Properties and Select Java Build Path
3. Double click on JRE System Library and Select Java1.8 version in
Execution environment
4. Click on ‘Finish’ and ‘Apply and Close’

TYPES OF LIBRARIES
==> We have 2 types of Libraries
1. JRE System Library
2. Referenced Libraries
1. JRE System Library
==> All predefined packages and classes are present in JRE System
Library.
2. Referenced Libraries
==> All external JAR files are stored in Referenced Libraries.

CONVERSION OF FILES
==> There are 2 conversions in Java.
1. Source file to Class file.
2. Class file to Source file.
✓ After creation of Java file we are using Complier to create Class file.
✓ Project can contain two types of files, Source file as well as Class
file.
✓ Source file is to read the code.
✓ Class file is used to execute the code
✓ After converting the project into JAR file, JAR file will not contain
Source code to read a code. So we need to go with De-Compiler.
✓ De-Compiler is used to convert Class file into Source file for
readability purpose.
PERSPECTIVE
==> Perspectives are used to decide which type of application we are
developing.
==> Perspectives are used to decide type of an application which can be
developed in Eclipse IDE.
==> There are 2 types of perspectives
1. Java Perspective
2. JavaEE perspective
1. Java Perspective
✓ Java Perspective is used to develop the application which will work
without internet (Standalone Application).
✓ In Java Perspective folders are represented as Packages.
2. Javaee Perspective
✓ JavaEE Perspective is used to develop the application which will
work with internet (Web Application).
✓ In JavaEE Perspective folders are represented as APIs.

Java Perspective Package java.util

Folder
JavaEE Perspective API utilityAPI

NOTE:
✓ JavaEE stands for ‘Java Enterprise Edition’.
✓ Advance Java can be called as JEE / J2EE.
HOW TO SELECT JAVAEE PERSPECTIVE IN ECLIPSE
✓ Open Eclipse > Click the window Right side of ‘Quick access’
✓ Window Perspective ----------- > Open Perspective

Open < JavaEE < Others

✓ Help >Install new software’s > Drag the ‘Work with’ tagbar

Install < Click on Web,XML < Click on All available sites

(API) APPLICATION PROGRAMMING INTERFACE


✓ API is used to share the information from one application to another
application.
✓ API is a mediator between two applications.
✓ The process of sharing the information from one application with
another application technically referred as Communication Medium.
NOTE: ==> The API terminology is present in JavaEE Perspective.
FOLDER

Java Perspective JavaEE Perspective

Package API

Collection of Classes Collection of Classes


and Interfaces and Interfaces

Super class Sub class Helper class Implementation class

✓ The API contains collection of classes and interfaces.


✓ Classes are defined as Helper and Implementation class.
✓ The classes which contain common properties is known as Helper
class.
✓ The classes which contain specific properties is known as
Implementation class.
✓ The collection of non-static, abstract, static and final variables is
known as Interface.
✓ The combination of Helper class and Implementation class, Interface
is known as Application Programming Interface.
JAVA PERSPECTIVE JAVA PERSPECTIVE

Super class Helper class


Sub class Implementation class

Interface Interface

Package API

DRIVERS
✓ Drivers are nothing but Translators.
✓ Drivers are used to convert one type of language into another type of
language.
✓ The process of converting one type of language into another type of
language is known as Translation.
Examples:

✓ Source code ------- > Compiler ---------- > Byte code


✓ Byte code --------- >De-Compiler ---------- > Source code
✓ Byte code ---------- > JVM ---------- >Binary code

JDBC ARCHITECTURE
✓ JDBC stands for “Java Database Connectivity”
✓ JDBC is used to connect Java application with Database application.
✓ It is used to store the data inside Database.
✓ The application which we are using to collect the user information it
cannot be stored the data by itself. So we need to go with Database.
✓ To understand the process of JDBC Architecture we have to follow
major four components.

COMPONENTS OF JDBC ARCHITECTURE


1. Java Application
2. JDBC API
3. JDBC Drivers
4. Database

1. JAVA APPLICATION
✓ Java application is used to collect user information.
✓ The data which is collected by the Java application we have to store it
in database.
✓ We can collect the data by the Java application in two ways.
Scanner ------- > Basic level
HTML ------> Higher level
2. JDBC API
✓ JDBC API is used to sharing the user information from Java
application to Database application.
✓ The JDBC API will represents in JavaEE perspective.
✓ JDBC API is equal (or) corresponds of java.sql package.
✓ Classes and Interfaces which are present in JDBC API (java.sql
package).

1. Driver Manager Helper class


2. Connection
3. Statement
4. Prepared Statement Interfaces
5. Callable Statement
6. Result Set

3. JDBC DRIVERS
✓ JDBC Drivers are used to convert Java information into SQL
information (or) Java Language into SQL language (or) Java Calls into
SQL Calls

NOTE: The data which is collected in Java application is present in


Java language, Java language cannot be understandable by Database, It
is understand only Query language, So to make Database to understand
Java instruction we need to convert into SQL instruction, So we make
use of JDBC drivers.

4. DATABASE
✓ Database is used to store the data permanently.
✓ In Database we have two types.
1. Oracle
2. MySQL
✓ To store the data in the Database we require DBMS(Data Base
Management System) to access (or) manage the data.
✓ To working with MySQL Database we need RDBMS(Relational Data
Base Management System) to manage and store the data in table
format.
✓ To get the RDBMS in system and working with MySQL we have to
install SQLyog Application.
✓ To perform the operations on the Database we have to use
SQL(Structured Query Language).

WORKING WITH SQLYOG APPLICATION


✓ We approach SQLyog application to communicate with MySQL
database.
✓ To communicate with any database we require the suitable RDBMS.
✓ RDBMS cannot be accessed directly, they stored inside an
application inorder to use that we have to install the specific
application.
Types of Database Software DBMS

Oracle SQL Plus RDBMS with Oracle


MySQL SQLyog RDBMS with MySQL
SCHEMA
 The process of creating database inside a database is known as
Schema.
STEPS TO CREATE DATABASE INSIDE MYSQL DATABASE
1. Open the SQLyog application
2. Select root@localhost. Right click on it.
3. Select an option as “Create Database”.
4. Specify the database name and click on Finish.
5. We have to use datatype to store data inside a table.
6. Datatypes are different compare to Java language and MySQL
database.
7. Scale (or) Precision are mandatory when we are using “double”
datatype.
EmpId EmpName EmpSal DeptNo

Java int “String” double Int

SQL int “variable” double int

STEPS TO CREATE TABLE INSIDE DATABASE


1. Select the Database and Right click on it.
2. Select an option called as “Create Table”.
3. Specify the field values by providing datatype, fieldname, length,
primary key, NOT NULL values.
4. After the field values click on “Create Table”.
5. Specify the table name and click on Finish.
6. We will get a message as “Table created successfully”.
CRUD OPERATIONS
1. Create
2. Read
3. Update CRUD operations
4. Delete

1.Create:
SYNTAX FOR INSERT QUERY WITH EXAMPLE INSERT INTO
DATABASE_NAME.TABLE_NAME INTO VALUES(V1,V2,…..,Vn);
Eg: insert into teja15.employee values (101,’RAM’,50000,’HYD’);

2. Read
SYNTAX FOR SELECT QUERY WITH EXAMPLE SELECT
*/COLUMN_NAME FROM
DATABASE_NAME.TABLE_NAME WHERE <CONDITION>;
Eg: select * from teja15.employee where deptNo=10;

3.Update
SYNTAX FOR UPDATE QUERY WITH EXAMPLE UPDATE
DATABASE_NAME.TABLE_NAME SET COLUMN_NAME = VALUE
WHERE <CONDITION>;
Eg: update teja15.employee set location = ‘DLH’ where location = ‘HYD’;

4. Delete
SYNTAX FOR DELETE QUERY WITH EXAMPLE DELETE FROM
DATABASE_NAME.TABLE_NAME WHERE< CONDITION >;
Eg: delete from teja15.employee where empId=101;

OPERATIONS
On the database we can perform two operations.
1. Read operation
2. Write operation
✓ To perform write operation we are using insert, update,
delete queries
✓ To perform read operation we are using select query.
✓ To alter the table Select Table Right click Alter table option
✓ Primary key value which is used to allow unique values in the specific
columns.
✓ NOT NULL is used to doesn’t allow NULL values in the specific column.
✓ After creating the table user can see his data by setting
“View data”. STEPS TO VIEW DATA
✓ Select Table Right click Select View Data option
✓ To see the modification on the database for values we have to keep on
refreshing the table.

URL
✓ URL stands for ‘Uniform Resource Locator’.
✓ URL contains complete information about the application.
✓ URL helps to the API to share the information from one application
to another application.
✓ It is mandatory to use URL to connect with Java application and
Database application.
✓ Every database will contain four information.
1. Protocol
2. Host information
3. Port number
4. User information

✓ These all the information present in the URL.

1. PROTOCOL
✓ Set of rules which must be followed to access an application.
✓ User information are storing inside database because we need to
connect with database.
✓ The database protocol is JDBC.
✓ In database we have two types
1. Oracle
2. MySql
✓ To give more clarity about the URL we have to use Sub-protocol.
✓ Syntax for Protocol is Protocol: Sub-Protocol
Ex: JDBC:MySql,
JDBC:Oracle
✓ The protocol for server is ‘https’.
2. HOST INFORMATION
✓ Host Information is the way of accessing an application.
✓ We have two types of host information.
1. Local Host
2. Remote Host
1. Local Host
✓ If an application is present inside user system, then we are going to
use Local host.
✓ To access Standalone application, we make use of Local host.
2. Remote Host
✓ If an application is present inside server we are going to use Remote
host.
✓ To access Web application, we make use of Remote host.
3. PORT NUMBER
✓ Port number is used to open the gateway of the Database.
✓ Each and every database they contain the gateway.
✓ To store the user data inside database first we need to get in, for that
we have to open the gateway by using port number.
✓ For a MySQL server, there are two port numbers 3306 and 3307
4. USER INFORMATION
✓ It is used to provide more security for an application.
✓ All the applications are already present with basic security by port
number. To increase more security we make use of user information.
✓ The combination of protocol, host information, port number, user
information is known as URL
✓ Syntax for URL is
Protocol : Sub-Protocol : // Host info : Port Number ? User info

EXAMPLES
For Example 1,
If programmer is using MySQL database the protocol is “jdbc : mysql” and
host information is “localhost” ( Because SQLyog application is present in
the user system) and port number will be “3306 (or) 3307” and the
username for MySQL database is “root” and password is “12345”. jdbc :
mysql : // localhost : 3306 ? user = root & password = 12345
For Example 2,
If programmer is using Oracle database the protocol is “jdbc : oracle” and
host information is “localhost” and the port number of oracle database is
“1521” and the username is “SCOTT” and password is “TIGER”.
jdbc : oracle : // localhost : 1521 ? user = SCOTT & password = TIGER

STEPS OF JDBC
→We can develop applications in two approach.
1. Without using Inbuilt code
2. With using Inbuilt code
✓ Without using inbuilt code if we develop an application it will take
more time.
✓ With using inbuilt code if we develop an application, it will take less
time.
✓ All the developers will always prefer to go with using inbuilt code.
STEPS

1. ESTABLISHING CONNECTION
✓ To pass the query from Java application to Database application we
have to establish a connection first.
✓ To establish a connection we are using Connection interface which iss
present in java.sql package.
✓ For a Connection interface there is a helper class called as
DriverManager.
✓ DriverManager having a method called as getConnection().
✓ It can accept URL as argument.
1. getConnection( String URL);
2. getConnection( String URL, String user, String password);
3. getConnection( String URL , Properties propt);
✓ getConnection() is responsible to throw checked exception called
as SQLException.
✓ The return type of getConnection() method is Connection interface.
2. CREATE A PLATFORM
✓ Platforms are used to carry the query from Java application to
Database application.
✓ Java application contains both Java code as well as SQL code.
✓ Java compiler can understand only Java code.
✓ To make SQL query to understand the compiler we make use of
Platforms.

TYPES OF PLATFORMS
1. Statement Platform
2. Prepare Statement Platform
3. Callable Statement Platform
✓ The SQL queries which are present in Java program can
understandable by Database.
✓ If a query contains hardcoded value, we prefer Statement platform.
✓ If a query contains runtime values, we prefer PreparedStatement
platform.
✓ If a query contains hardcoded as well as runtime value, we prefer
CallableStatement platform.
NOTE :
The main use of platform is to carry the query from Java application to
Database application.
-------------------------------------------------------------------------------------------
HARDCODED VALUE
→The value which is entered by the Developer is known as Hardcoded
value.
Eg: int a = 50;

RUNTIME VALUE
→The value which is entered by the User is known as Runtime value.
Eg: int a = sc.nextInt();

PLATFORMS
Statement Hardcoded value
PrepareStatement Runtime value
CallableStatement Hardcoded + Runtime value
public class QueryExecution {
public static void main(String[] args) {

4.EXECUTION OF QUERY

OUTPUT
Connection Established...!
Platform Created...!
Query Executed...!
4. PROCESS OF RESULTANT DATA (OPTIONAL)
==> It is an optional step in JDBC because resultant data will not be created
for all the queries, it creates only for select query.
NOTE:
✓ The data which is present in the database is known as Actual data.
✓ Actual data is permanent data.
✓ The query after reaching to the database there are three operations
will get performed.
1. Compilation of query
2. Execution of query
3. Store the output in Buffer memory
✓ Output will get generated only for read operation.
✓ The data which is present in the Buffer memory is known as
Resultant data.
✓ Resultant data is temporary data
BUFFER MEMORY
✓ Buffer memory will get created after performing the read operation.
✓ There are two pointers in Buffer memory
1. BFR (Before First Record)
2. ALR (After Last Record)
RESULT SET
✓ ResultSet is an interface which is present in java.sql package
✓ ResultSet interface is used to store the resultant
data.
METHODS OF RESULT SET
1. next( ) boolean
2. last( ) boolean
3. beforeFirst( ) void
4. getter ______
getInt(column_number,column_name)
getString(column_number,column_name)
getDouble(column_number,column_name)
getFloat(column_number,column_name)
1. next( )
✓ It is used to move the cursor from one record to another record,
return type is boolean.
2. last( )
✓ It is used to move the cursor to the last record which is present in
Buffer memory, return type is Boolean.
3. beforeFirst( )
✓ It is used to move the cursor from current record to BFR
pointer, return type is void.
4. getter methods
✓ They are used to get the data from the Buffer memory based on
column datatype.
✓ Getter methods are overloaded methods, we can pass any value
as follows.
1. Column_number
2. Column_name

public class Selection {

public static void main(String[] args) {


String url = "jdbc:mysql://localhost:3306?user=root&password=12345";
String query = "select * from teja15.employee where empId=105";
try {
Connection connection = DriverManager.getConnection(url);
System.out.println("Connection Established...!!!");
Statement stmt = connection.createStatement();
System.out.println("Platform Created");
ResultSet rs = stmt.executeQuery(query);
if(rs.next()) {
System.out.println("Valid +Employee ID.....");
System.out.println("***************");
int id = rs.getInt("empId");
String name = rs.getString("empName");
double sal = rs.getDouble("empSal");
int dept = rs.getInt("deptNo");
String loc = rs.getString("location");
System.out.println("Employee ID : "+id);
System.out.println("Employee Name : "+name);
System.out.println("Employee Salary : "+sal);
System.out.println("Employee Dept No : "+dept);
System.out.println("Employee Location : "+loc);
} else
{ System.err.println("Invalid Employee ID...!!!");
} }
catch (SQLException e) {
e.printStackTrace();
} }}
PREPARED STATEMENT
insert into teja15.employee(101,’xyz’,1000.0,10,’HYD’)
{Hardcode values}
insert into teja15.employee(?,?,?,?,?) {Placeholders Runtime Scanner
class}

STATEMENT PREPARED STATEMENT


We are using hard coded values We are using run time values
Placeholders are not present in
Placeholders are present Statement platform
inPreparedStatement
platform createStatement()
prepareStatement(query) is a argument is a no argument method
method
Pass the query to the platform Already query as passed
Return type is Statement platform Return type is
PreparedStatement platform

HOW TO ASSIGN VALUES TO THE PLACEHOLDERS


setter setInt(placeholder_position,value)
setString(placeholder_position,value)
setDouble(placeholder_position,value)
setFloat(placeholder_position,value)
package org.jdbc.prepared;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class PStmtProgram {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306?user=root&password=12345";
String query = "insert into teja15.employee values(?,?,?,?,?) ";
try {
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected...!");
PreparedStatement ps = connection.prepareStatement(query);
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Employee ID : ");
int id = sc.nextInt();
ps.setInt(1,id);
System.out.println("Enter the Employee Name : ");
String name = sc.next();
ps.setString(2, name);
System.out.println("Enter the Employee Salary : ");
double sal = sc.nextDouble();
ps.setDouble(3,sal);
System.out.println("Enter the Employee Dept : ");
int dept = sc.nextInt();
ps.setInt(4, dept);
System.out.println("Enter the Employee Location : ");
String loc = sc.next();
ps.setString(5, loc);
ps.executeUpdate();
System.out.println("Data Inserted...!");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
OUTPUT
Connected...!
Enter the Employee ID : 109
Enter the Employee Name : SIMON
Enter the Employee Salary : 40000 Enter the Employee
Dept : 10 Enter the Employee Location : GURGAON Data
Inserted...!
JDBC PROGRAM TO DELETE

package org.jdbc.prepared; import java.sql.Connection;


import java.sql.DriverManager; import
java.sql.PreparedStatement; import java.sql.SQLException;
import java.util.Scanner; public class PStmtDelUMob {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306?user=root&password=12345";
String query = "delete from teja15.user where uMobile=?";
try {
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected...");
PreparedStatement ps =
connection.prepareStatement(query);
Scanner sc = new Scanner(System.in);

System.out.println("Enter
the Mobile Number to
Delete : "); String
mobile = sc.next();
ps.setString(1, mobile);
int num =
ps.executeUpdate();
if(num > 0) {
System.out.println("Record deleted...");
} else {
System.err.println("Invalid Record...");
} }
catch (SQLException e) {
e.printStackTrace();
} }
}
OUTPUT
Connected...
Enter the Mobile Number to Delete
: 7345234955 Record deleted...
UPDATE SALARY
package org.jdbc.prepared;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;
import java.util.Scanner;

public class PStmtUpdSalOTP {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306?user=root&password=12345";
String query = "select * from teja15.employee where empDOB>?";
try {
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected");
PreparedStatement ps = connection.prepareStatement(query);
Scanner sc = new Scanner(System.in);
System.out.println("Enter the DOB : ");
String dob = sc.next(); ps.setString(1,dob);
ResultSet rs = ps.executeQuery();
if(rs.last()) {
rs.beforeFirst();
while(rs.next()) {
System.out.println("Emp Id : "+rs.getInt(1));
System.out.println("Emp Name : "+rs.getString(2));
System.out.println("Emp Sal : "+rs.getDouble(3));
System.out.println("Emp Dept : "+rs.getInt(4));
System.out.println("Emp Location : "+rs.getString(5));
System.out.println("Emp DOB : "+rs.getString(6));
System.out.println("Emp Mobile : "+rs.getString(7));
System.out.println("***************");
System.out.println("Enter the Mobile Number : ");
String mobile = sc.next();
if(mobile.equals(rs.getString(7))) {
Random r = new Random();
int otp = r.nextInt(10000);
if(otp<1000) {
otp+=1000;
}
System.out.println("OTP : "+otp);
System.out.println("Enter
the OTP for verification : ");
int user = sc.nextInt();
if(user == otp) {
query = "update teja15.employee set empSal=empSal+empSal*0.1 where
empMOB='"+mobile+"'and empDOB>'"+dob+"'";
PreparedStatement ps1 = connection.prepareStatement(query);
ps1.executeUpdate();
System.out.println("Salary Updated...!");
} else
{
System.err.println("Invalid OTP...!!!");
} }else
{
System.err.println("Invalid Mobile Number...!!!");
} } }
else {
System.err.println("No Data Found");
} }
catch (SQLException e) {
e.printStackTrace();
} }}

OUTPUT
Connected Enter the DOB : 2004-12-31
Emp Id : 102 Emp Name : ASHOK
Emp Sal : 200000.0
Emp Dept : 20
Emp Location : BANGLORE Emp DOB :
2006-05-31
Emp Mobile : 9876543210
***************
Enter the Mobile Number :
9876543210 OTP : 9688
Enter the OTP for verification :
9688 Salary Updated...!

You might also like