Final 214 6 1 - Removed

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 23CSR306-JAVA PROGRAMMING LABORATORY

Ex no: 6.3
PROGRAMS USING JDBC
Date:
QUESTION:
Consider the employee table:

• Write a Java program to create the employee table and insert the 3 rows given in the table
using Prepared Statement.
• Create a Stored Procedure to calculate the tax for the salary of the employees in the
employee table and update the ‘tax_per month’ column. Invoke the stored
procedure using Callable Statement. The tax is calculated based on the table given below:

AIM:
To develop java program that implements the above table using JDBC.

CODE:
DBUtil.java
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil{
private static Connection conn;
public static Connection getConnection(){ try{
Class.forName("com.mysql.cj.jdbc.Driver"); conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/experiment_23", "root", "toor");
}catch(ClassNotFoundException e){
System.out.println(e);
}catch(SQLException e){
System.out.println(e);
}
return conn;}}
Main.Java
import java.sql.*;
public class Main{
public static void main(String[] args){ try{
Connection conn = DBUtil.getConnection(); Statement
st = conn.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS employee (empid INT PRIMARY KEY,
name VARCHAR (21), salary INT, tax_per_month INT);");
PreparedStatement pst = conn.prepareStatement("INSERT IGNORE INTO employee VALUES
(?, ?, ?, ?);");
pst.setInt(1, 101);
pst.setString(2, "Arun");
pst.setInt(3, 35000);

ROLLNO:717823P146
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 23CSR306-JAVA PROGRAMMING LABORATORY

pst.setInt(4, 0);
pst.executeUpdate();
pst.setInt(1, 102);
pst.setString(2, "Deepak");
pst.setInt(3, 41500);
pst.setInt(4, 0);
pst.executeUpdate();
pst.setInt(1, 103);
pst.setString(2, "Ashik");
pst.setInt(3, 55000);
pst.setInt(4, 0);
pst.executeUpdate();
CallableStatement cst = conn.prepareCall("{CALL CalculateTax()}"); cst.execute();
ResultSet rs = st.executeQuery("SELECT * FROM employee"); while(rs.next()){
System.out.println("[empid=" + rs.getInt(1) + ", name=" + rs.getString(2) + ", salary=" +
rs.getInt(3) + ", tax_per_month=" + rs.getInt(4) + "]");}
st.close();
pst.close();
cst.close();
rs.close();
conn.close();
}catch(SQLException e){
System.out.println(e);
}}}
STORED PROCEDURE:-
DELIMITER $$
BEGIN DECLARE tax_rate FLOAT;
UPDATE employee
SET tax_per_month = CASE
WHEN Salary < 50000 THEN Salary * 0.02
WHEN Salary >= 50000 THEN Salary *
0.023ELSE 0
END;
DELIMITER $$

OUTPUT:

Result:
Thus, the Java programs using the JDBC has been successfully developed and the output was verified.

ROLLNO:717823P146

You might also like