Practical No.
7
[Link] a program to create employee table in database
having two columns “product_id” and “product_name”.
Program:
import [Link].*;
public class CreateEmployeeTable {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection conn = [Link]
("jdbc:mysql://localhost:1334/sakila", "root",
"root@shreyas");
Statement statement = [Link]();
String sql = "CREATE TABLE employee (" +
"product_id INT AUTO_INCREMENT PRIMARY KEY," +
"product_name VARCHAR(255) NOT NULL)";
[Link](sql);
[Link]("Table 'employee' created successfully!");
[Link]();
[Link]();
} catch (SQLException | ClassNotFoundException e) {
[Link]();
}}
Output:
[Link] a program to display the name and roll_no of students
From “studentstable” having percentage>70.
import [Link].*;
public class DisplayStudents {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection conn = [Link]
("jdbc:mysql://localhost:1334/sakila",
"root", "root@shreyas");
Statement statement = [Link]();
String sql = "SELECT name, roll_no FROM studenttable WHERE
percentage > 70";
ResultSet resultSet = [Link](sql);
[Link]("Students with percentage > 70:");
[Link]("Name\t\tRoll No");
[Link]("---------------------------");
while ([Link]()) {
String name = [Link]("name");
int rollNo = [Link]("roll_no");
[Link](name + "\t\t" + rollNo);
}
[Link]();
[Link]();
[Link]();
} catch (SQLException | ClassNotFoundException e) {
[Link]();
}
}
}
Output:
[Link] a program to update name of a student from Rama to
Rohan.
import [Link].*;
public class UpdateStudentName {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection conn = [Link]
("jdbc:mysql://localhost:1334/sakila", "root", "root@shreyas");
String sql = "UPDATE studenttable SET name = ? WHERE name = ?";
PreparedStatement preparedStatement =
[Link](sql);
[Link](1, "Rohan");
[Link](2, "Rama");
int rowsAffected = [Link]();
if (rowsAffected > 0) {
[Link]("Name changed from Rama to Rohan");
} else {
[Link]("No records found with name Rama");
}
[Link]();
[Link]();
} catch (SQLException | ClassNotFoundException e) {
[Link](); } }}
Output:
[Link] a program to delete all record for a product whose “price
is greater than 1000” and Id is “P1234”.
import [Link].*;
public class DeleteProductRecords {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection conn =
[Link]("jdbc:mysql://localhost:3306/sakila",
"root", "root@shreyas");
String sql = "DELETE FROM product WHERE product_id = ?
AND price > ?";
PreparedStatement preparedStatement =
[Link](sql);
[Link](1, "P1234");
[Link](2, 1000.0);
int rowsAffected = [Link]();
[Link]("Record deleted successfully");
[Link]();
[Link]();
} catch (SQLException | ClassNotFoundException e) {
[Link]();
}
}
}
Output: