0% found this document useful (0 votes)
8 views

Java2 Exer

The program develops a Java application using JDBC that connects to a database and allows users to perform CRUD operations on an employee table through a menu. It uses prepared statements to insert, update, delete and retrieve data from the table.

Uploaded by

pp5006277
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java2 Exer

The program develops a Java application using JDBC that connects to a database and allows users to perform CRUD operations on an employee table through a menu. It uses prepared statements to insert, update, delete and retrieve data from the table.

Uploaded by

pp5006277
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Ex no:

PROGRAM USING JDBC CRUD OPERATIONS


Date:

Question
Develop a Java program to connect with database and retrieve following details:
• Write a Java code to insert records by reading input from user.
• Display all the details which are stored in Nobel Prize table.
• Display the details of the Nobel Prize winners who got for the subject Peace.
• Delete the NobelPrize winners who got NobelPrize before 1930.

Aim
To write a java program to connect database and perform CRUD operations in NobelPrize table.

Program / Source Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class noble_prize {
public static Connection getConnect() throws Exception
{
String url="jdbc:mysql://localhost:3306/noble";
String username="root";
String password="root";
Connection con=DriverManager.getConnection(url,username,password);
return con;
}
public static void create_table() throws Exception
{
Connection con=getConnect();
String query="create table noble_prize(Name varchar(50),Year int,Subject
varchar(50))";
Statement s=con.createStatement();
s.execute(query);
con.close();
}
public static void insert(String name,int year,String subject) throws Exception
{
Connection con=getConnect();
String query="insert into noble_prize values(?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1,name);
ps.setInt(2,year);
ps.setString(3,subject);
ps.execute();
con.close();

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


}
public static void display() throws Exception
{
Connection con=getConnect();
String query="select * from noble_prize";

System.out.println("===============================================");
System.out.println("Name\t\t\tYear\t\tSubject");

System.out.println("===============================================");
Statement s=con.createStatement();
ResultSet rs=s.executeQuery(query);
while(rs.next())
{
System.out.println(rs.getString(1)+"\t\t"+rs.getInt(2)+"\t\t"+rs.getString(3));
}

System.out.println("===============================================");
con.close();
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
try {
create_table();
for(int i=0;i<5;i++) {
System.out.print("Enter name: ");
String s=sc.nextLine();
System.out.print("Enter year: ");
int n=sc.nextInt();
sc.nextLine();
System.out.print("Enter subject: ");
String sub=sc.nextLine();
insert(s,n,sub);
}
insert("Rabindhranath Tagore",1917,"Literature");
display();
Connection con=getConnect();
String query1="select * from noble_prize where Subject='Peace'";
Statement s=con.createStatement();
ResultSet rs=s.executeQuery(query1);
rs.next();
System.out.println("\nPeace winners: "+rs.getString(1)+" "+rs.getInt(2));
String query2="delete from noble_prize where Year<1930";
s.executeUpdate(query2);
display();
}
catch(Exception e)
{
e.printStackTrace();
}
}}

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING PREPARED STATEMENT IN JDBC
Date:

Question
Given the following table containing information about employees of an organization,
develop a small java application, using JDBC, which displays a menu for the user consisting
of following options: (Use Prepared Statement for Executing Queries)
1. Add Record 2. Modify Record 3. Delete Record
4. Display one Record 5. Display All 6. Exit

Aim
To write a java program to connect database and perform CRUD operations using prepared
statement.

Program / Source Code:


package mod2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class employee {


public static void create_table(Connection con) throws Exception{
String query="create table Employee(Emp_No int,First_Name
varchar(50),Last_Name varchar(50),Date varchar(15),Designation varchar(30),Dept
varchar(20),Basic_salary int)";
Statement s=con.createStatement();
s.execute(query);
}
public static void insert(Connection con,int Emp_no,String name1,String name2,String
date,String desig,String dept,int salary) throws Exception
{
String query="insert into Employee values(?,?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1,Emp_no);
ps.setString(2, name1);
ps.setString(3, name2);
ps.setString(4,date);
ps.setString(5,desig);
ps.setString(6,dept);
ps.setInt(7,salary);
ps.executeUpdate();
}
public static void display(Connection con,int id) throws Exception{
String query="select * from Employee where Emp_no=?";
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1,id);

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


ResultSet rs=ps.executeQuery();
rs.next();
System.out.println("Employee no: "+rs.getInt(1)+"\nDesignation
"+rs.getString(5)+"\nDepartment: "+rs.getString(6)+"\nSalary: "+rs.getInt(7));
}
public static void update(Connection con,int id,String desig,int salary) throws Exception {
String query1="update Employee set Designation=? where Emp_no=?";
PreparedStatement ps1=con.prepareStatement(query1);
ps1.setString(1,desig);
ps1.setInt(2,id);
ps1.executeUpdate();
String query3="update Employee set Basic_salary=? where Emp_no=?";
PreparedStatement ps3=con.prepareStatement(query3);
ps3.setInt(1,salary);
ps3.setInt(2,id);
ps3.executeUpdate();
}
public static void delete(Connection con,int id) throws Exception
{
String query="delete from Employee where Emp_no=?";
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1,id);
ps.executeUpdate();
}
public static void displayAll(Connection con) throws Exception
{
String query="select * from Employee";
Statement s=con.createStatement();
ResultSet rs=s.executeQuery(query);
while(rs.next())
{
System.out.println("Employee no: "+rs.getInt(1)+" First Name:
"+rs.getString(2)+" LastName "+rs.getString(3)+" Date "+rs.getString(4)+" Designation
"+rs.getString(5)+" Department: "+rs.getString(6)+" Salary: "+rs.getInt(7));
}
}

public static void main(String[] args) {


String url="jdbc:mysql://localhost:3306/Employees";
String username="root";
String password="root";
Scanner sc=new Scanner(System.in);
try {
Connection con=DriverManager.getConnection(url,username,password);
System.out.println("Choices\n1.Add employee\n2.Update record\n3.Remove
employee\n4.Display employee detail\n5.Display all\n");
create_table(con);
insert(con,1001,"Ashish","Kulkarni","19-04-2024","Architect","R&D",50000);
insert(con,1002,"Sushma","Shah","19-01-2024","Officer","Purchase",30000);
insert(con,1003,"Rahul","G","19-01-2024","Clerk","Stores",10000);
insert(con,1004,"Chahat","Punja","19-01-2024","Manager","HR",12000);

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


insert(con,1005,"Ranjan","Srivastava","19-01-2024","Clerk","Accounts",20000);
insert(con,1006,"Suman","J","19-01-2024","Officer","Accounts",23000);
System.out.print("Enter your choice: ");
int ch=sc.nextInt();
while(ch!=0) {
if(ch==1)
{
System.out.print("Employee ID: ");
int id=sc.nextInt();
sc.nextLine();
System.out.print("Employee’s First Name: ");
String fname=sc.nextLine();
System.out.print("Employee’s last Name: ");
String lname=sc.nextLine();
System.out.print("Join Date: ");
String date=sc.nextLine();
System.out.print("Department: ");
String dept=sc.nextLine();
System.out.print("Designation: ");
String desig=sc.nextLine();
System.out.print("Salary: ");
int salary=sc.nextInt();
insert(con,id,fname,lname,date,dept,desig,salary);
System.out.print("Inserted successfully");
}
else if(ch==2)
{
System.out.print("Enter emp_id: ");
int id=sc.nextInt();
display(con,id);
sc.nextLine();
System.out.print("Enter designation: ");
String d=sc.nextLine();
System.out.print("Enter salary: ");
int s=sc.nextInt();
update(con,id,d,s);
System.out.print("Updated successfully");
}
else if(ch==3)
{
System.out.print("Enter emp_id: ");
int id=sc.nextInt();
delete(con,id);
System.out.print("Deleted successfully");
}
else if(ch==4)
{
System.out.print("Enter emp_id: ");
int id=sc.nextInt();
display(con,id);
}

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


else if(ch==5)
{
displayAll(con);
}
System.out.print("\nEnter your choice: ");
ch=sc.nextInt();
}
con.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING CALLABLE STATEMENT IN JDBC
Date:

Question
1) Develop a Java program to connect with database and retrieve following details: 1) Add a new book
‘HTML, CSS & JavaScript’ by Laura Lemay, Prentice Hall, Rs.250.00 using Prepared Statement.
2) Display all the details which are stored in Books table. 3) Create a Procedure to increase the price
of books by Rs.200. 4) Create a Procedure to add new record into table. 5) Execute procedures using
Callable Statement.

Aim
To write a java program to connect jdbc and perform CRUD operations using callable statement.

Program / Source Code:


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
public class BookProgram {
public static void main(String[] args){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/ajp";
String username="root";
String password="root";
Connection conn=DriverManager.getConnection(url,username,password);
Scanner sc=new Scanner(System.in);
System.out.println("Adding records to the table using prepared statement:");
System.out.print("Entrer title: ");
String title=sc.nextLine();
System.out.print("Enter author :");
String author=sc.nextLine();
System.out.print("Enter publication :");
String publication=sc.nextLine();
System.out.print("Enter price :");
float price=sc.nextFloat();
String query1="INSERT INTO book VALUES(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(query1);
ps.setString(1, title); ps.setString(2, author); ps.setString(3,
publication); ps.setFloat(4, price);
int rows=ps.executeUpdate();
if(rows>0) System.out.println("Inserted successfully");
else System.out.println("Rows not inserted");
System.out.println("\nUpdating price");
System.out.print("Enter title: "); title=sc.nextLine();
CallableStatement cs=conn.prepareCall("{call updatePrice(?)}");
cs.setString(1, title); cs.execute();
String query2="SELECT * FROM book";
PreparedStatement ps1=conn.prepareStatement(query2);

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


ResultSet rs=ps1.executeQuery();
System.out.println("Displaying book table : ");
while(rs.next()){
System.out.printf("%-40s %-20s %-20s %.2f\n",rs.getString("title"),
rs.getString("author"),rs.getString("publication"),rs.getFloat("price"));
System.out.println("\nAdding records to the table using callable statement:");
System.out.print("Enter title: ");
title=sc.nextLine();
System.out.print("Enter author :");
author=sc.nextLine();
System.out.print("Enter publication :");
publication=sc.nextLine();
System.out.print("Enter price :");
price=sc.nextFloat();
CallableStatement cs1=conn.prepareCall("{call insertbook(?,?,?,?)}");
cs1.setString(1, title);cs1.setString(2, author);
cs1.setString(3, publication);
cs1.setFloat(4, price); cs1.execute();
PreparedStatement ps2=conn.prepareStatement(query2);
ResultSet rs1=ps2.executeQuery();
System.out.println("Displaying book table : ");
while(rs1.next())
System.out.printf("%-40s %-20s %-20s %.2f\n",rs1.getString("title"),
rs1.getString("author"),rs1.getString("publication"),rs1.getFloat("price"));
sc.close(); rs.close(); rs1.close(); ps.close(); ps1.close(); ps2.close();
cs.close();cs1.close();conn.close();
}}}}}}catch(Exception e){ e.printStackTrace(); }
Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Write a Java program to test the function using JUnit & check whether it is finding the Nth Fibonacci
number.Try to fix the logical errors if any.

Aim
To write a java program that checks Fibonacci number is found correctly.

Program / Source Code:

public class FibonacciSequence {


public int nthFibonacci(int num) {
if (num == 1)
return 0;
else if (num == 2)
return 1;
return nthFibonacci(num - 1) + nthFibonacci(num - 2);
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class fibonacciTest {
@Test
public void test1() {
fibonacci f=new fibonacci();
int res=f.nthFibonacci(5);
assertEquals(3,res);
}
@Test
public void test2()
{
fibonacci f=new fibonacci();
int res=f.nthFibonacci(7);
assertEquals(8,res);
}
}

Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Create the class and implement the method to check given string is a palindrome and return the
result. Create a Junit test class to test the above class.

Aim
To write a java program that checks palindrome string is found correctly..

Program / Source Code:

public class MyUnit {


public boolean palindromeCheck(String input){
StringBuilder sb=new StringBuilder(input);
sb.reverse();
if(input.equals(sb.toString()))
return true;
else
return false;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeTest {
@Test
public void test1(){
MyUnit m=new MyUnit();
assertTrue(m.palindromeCheck("malayalam"));
}
@Test
public void test2(){
MyUnit m=new MyUnit();
assertFalse(m.palindromeCheck("Java"));
}}

Output

Result

Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question

Create the class and implement the method to find number of digits in a given string. Create a Junit
test class to test the above class.

Aim
To write a java program that checks number of digits is found correctly.

Program / Source Code:


public class Count {
public int digitCount(String input){
int cnt=0;
for(int i=0;i<input.length();i++){
if(input.charAt(i)>='0' && input.charAt(i)<='9') {
cnt+=1;
}
}
return cnt;
}}
public class CountTest {
@Test
public void test1() {
Count obj=new Count();
assertEquals(5,obj.digitCount("123abc@45"));
}
@Test
public void test2() {
Count obj=new Count();
assertEquals(0,obj.digitCount("Hello"));
}
}
Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Test the functions of Calculate class using JUnit. Print binary function is used to print the binary
equivalent of the given number. Note: Try to fix the logical errors in these functions.

Aim
To write a java program that checks the binary form of a number is found correctly.

Program / Source Code:

import java.util.Arrays;
public class Calculate {
public byte add(byte b1, byte b2) {
return (byte)(b1+b2);
}public short add(short b1,short b2) {
return (short)(b1+b2);
}public int[] printBinary(byte number) {
int[] result;
if (number < 16) result = new int[4];
else if (number < 32) result = new int[5];
else if (number < 64) result = new int[6];
else result = new int[7];
for(int i = result.length - 1; number > 0; i--) {
result[i] = number % 2;
number = (byte) (number / 2);
}
return Arrays.copyOfRange(result, i + 1, result.length);
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class CalculateTest {
byte input;
int[] expected;

public CalculateTest(byte input,int[] expected) {


this.input=input;
this.expected=expected;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] array= {{(byte)5,new int[]{1,0,1}},{(byte)15,new int[]{1,1,1,1}},{(byte)31,new
int[]{1,1,1,1,1}}};

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


return Arrays.asList(array);
}
Calculate c=new Calculate();
@Test
public void testAddByte() {
assertEquals(8,c.add((byte)3,(byte)5));
}
@Test
public void testAddShort() {
assertEquals(300,c.add((short)100,(short)200));
}
@Test
public void testPrintBinaryParameterized() {
assertArrayEquals(expected,c.printBinary(input));
}
}

Output:

Result

Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Create a test suite class for the above exercises 2 & 3 and test the methods.

Aim
To write a java program that test the program using suite method.

Program / Source Code:

public class MyUnit {


public boolean palindromeCheck(String input){
StringBuilder sb=new StringBuilder(input);
sb.reverse();
if(input.equals(sb.toString()))
return true;
else
return false;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeTest {
@Test
public void test1(){
MyUnit m=new MyUnit();
assertTrue(m.palindromeCheck("malayalam"));
}
@Test
public void test2(){
MyUnit m=new MyUnit();
assertFalse(m.palindromeCheck("Java"));
}}
public class Count {
public int digitCount(String input){
int cnt=0;
for(int i=0;i<input.length();i++){
if(input.charAt(i)>='0' && input.charAt(i)<='9') {
cnt+=1;
}
}
return cnt;
}}
public class CountTest {
@Test
public void test1() {
Count obj=new Count();
assertEquals(5,obj.digitCount("123abc@45"));

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


}
@Test
public void test2() {
Count obj=new Count();
assertEquals(0,obj.digitCount("Hello"));
}
}
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({PalindromeTest.class,CountTest.class})
public class TestSuite {
}

Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C

You might also like