1.
Write a JDBC application which will interact with Database and perform the
following task.
a. Create Student Table with RollNo, Name, and Address field and
insert few records.
b. Using Statement Object display the content of Record.
c. Using Statement Object Insert Two Record.
d. Using Statement Object Update One Record.
e. Using Statement Object Delete One Record.
f. Using Statement Object display the content of Record.
import [Link].*;
public class StudentJDBCApp
{
public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/testdb?";
String user = "testuser";
String password = "testpass";
try {
// Load MySQL JDBC Driver
[Link]("[Link]");
// Establish Connection
Connection con = [Link](url, user, password);
Statement stmt = [Link]();
// a. Create table
String createTable = "CREATE TABLE IF NOT EXISTS Student ("
+ "RollNo INT PRIMARY KEY, "
+ "Name VARCHAR(50), "
+ "Address VARCHAR(100))";
[Link](createTable);
[Link]("Table created successfully.");
// Insert few records
[Link]("INSERT INTO Student VALUES (1, 'Ravi',
'Hyderabad')");
[Link]("INSERT INTO Student VALUES (2, 'Sita',
'Chennai')");
[Link]("INSERT INTO Student VALUES (3, 'Kiran',
'Bangalore')");
[Link]("Initial records inserted.");
// b. Display records
[Link]("\nInitial Records:");
displayRecords(stmt);
1
// c. Insert 2 new records
[Link]("INSERT INTO Student VALUES (4, 'Meena', 'Pune')");
[Link]("INSERT INTO Student VALUES (5, 'Ramesh',
'Mumbai')");
[Link]("\nTwo new records inserted.");
// d. Update one record
[Link]("UPDATE Student SET Address = 'Delhi' WHERE
RollNo = 2");
[Link]("One record updated.");
// e. Delete one record
[Link]("DELETE FROM Student WHERE RollNo = 3");
[Link]("One record deleted.");
// f. Display updated records
[Link]("\nFinal Records:");
displayRecords(stmt);
// Close connection
[Link]();
} catch (Exception e) {
[Link]();
}
}
// Function to display records
public static void displayRecords(Statement stmt) throws SQLException {
ResultSet rs = [Link]("SELECT * FROM Student");
[Link]("RollNo\tName\tAddress");
while ([Link]()) {
int roll = [Link]("RollNo");
String name = [Link]("Name");
String address = [Link]("Address");
[Link](roll + "\t" + name + "\t" + address);
}
}
}