Faculty of Engineering & Technology
Subject Name: Enterprise Programming Using Java
Subject Code: 303105310
B.Tech. CSE Year: 3rd/ Semester: 5th
Experiment No :2
Problem Statement:
Write a program to demonstrate the use of Prepared Statement and Result Set interface.
Code:
package mypractices;
import java.sql.*;
import java.util.*;
public class dbexample2 {
public static void main(String [] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String conurl = "jdbc:mysql://localhost:3306/db101?useSSL=false";
Connection conn = DriverManager.getConnection(conurl, "root", "Alok@2004#join");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the empId");
int empId = sc.nextInt();
sc.nextLine();
System.out.println("Enter the empName");
String empName = sc.nextLine();
System.out.println("Enter the empAddress");
String empAddress = sc.nextLine();
String sql = "Insert into emp(empId, empName, empAddress)";
String insertSQL = "INSERT INTO emp (empid, empname, empaddress) VALUES (?, ?,
?)";
PreparedStatement pstmt = conn.prepareStatement(insertSQL);
pstmt.setInt(1, empId);
pstmt.setString(2, empName);
pstmt.setString(3, empAddress);
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println(rowsInserted + " row(s) inserted.");
} else {
System.out.println("Data entry failed.");
}
// Query and display the table contents
String selectSQL = "SELECT * FROM emp";
pstmt = conn.prepareStatement(selectSQL);
ResultSet rs = pstmt.executeQuery();
System.out.println("ID\tName\tAddress");
while (rs.next()) {
System.out.println(rs.getInt("empid") + "\t" + rs.getString("empname") +
"\t" + rs.getString("empaddress"));
Enrolment no.- 2203051050056 Student Name: Alok Tiwari Page:2
Faculty of Engineering & Technology
Subject Name: Enterprise Programming Using Java
Subject Code: 303105310
B.Tech. CSE Year: 3rd/ Semester: 5th
conn.close();
sc.close();
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}
}
Output:
Enrolment no.- 2203051050056 Student Name: Alok Tiwari Page:2