🔹Experiment 2: Java–MySQL Connectivity using JDBC(26/03/2026)
AIM
To develop a Java program to establish a connection with a MySQL database using JDBC and
perform basic database operations such as creating a table, inserting records, and retrieving data
using terminal-based execution.
Details
● Uses JDBC (Java Database Connectivity) API
● Establishes connection using MySQL driver
● Executes SQL queries using Statement
● Creates table if it does not exist
● Inserts records into the table
● Retrieves and displays records on terminal
Program
import [Link].*;
public class Experiment2 {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/studentdb";
String user = "root";
String password = "5Y$KUTLRvt4^f$1n";
try {
// Load JDBC driver (good for exams)
[Link]("[Link]");
// 1. Establish connection
Connection con = [Link](url, user, password);
[Link]("Connected successfully!");
// 2. Create statement
Statement stmt = [Link]();
// 3. Create table
String createTable = "CREATE TABLE IF NOT EXISTS students (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(50), " +
"age INT)";
[Link](createTable);
[Link]("Table created!");
// 4. Insert records
String insert = "INSERT INTO students(name, age) VALUES " +
"('Alice', 20), ('Bob', 22)";
[Link](insert);
[Link]("Data inserted!");
// 5. Retrieve data
ResultSet rs = [Link]("SELECT * FROM students");
[Link]("\nStudent Records:");
while ([Link]()) {
[Link](
[Link]("id") + " " +
[Link]("name") + " " +
[Link]("age")
);
// Close connection
[Link]();
} catch (Exception e) {
[Link]();
Output
Result
The program is successfully completed.