0% found this document useful (0 votes)
6 views2 pages

PracticalNo18 1

The document outlines a practical exercise for inserting and retrieving data from a database using JDBC in Java. It includes a program that connects to a MySQL database, creates a 'Student' table, inserts a record, and retrieves all records from the table. The program handles exceptions for SQL errors and driver not found scenarios.

Uploaded by

Ashish Mavani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

PracticalNo18 1

The document outlines a practical exercise for inserting and retrieving data from a database using JDBC in Java. It includes a program that connects to a MySQL database, creates a 'Student' table, inserts a record, and retrieves all records from the table. The program handles exceptions for SQL errors and driver not found scenarios.

Uploaded by

Ashish Mavani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Practical No.

: 18

Practical Name: Write a program to insert and retrieve data from database using JDBC.

Roll No.: 47

Student Name: Mavani Ashish Shantilal

Program:
import java.sql.*;

public class practical18_1 {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/student_DB";
String user = "root";
String password = "";

try {
Class.forName("com.mysql.cj.jdbc.Driver");

try (Connection conn = DriverManager.getConnection(url, user, password);


Statement stmt = conn.createStatement()) {

String createTableSQL = "CREATE TABLE IF NOT EXISTS Student (" +


"id INT PRIMARY KEY AUTO_INCREMENT," +
"name VARCHAR(50)," +
"age INT," +
"dept VARCHAR(50))";
stmt.executeUpdate(createTableSQL);

String insertSQL = "INSERT INTO Student (name, age, dept) VALUES ('Ashish', 18,
'Information Technology')";
stmt.executeUpdate(insertSQL);

String selectSQL = "SELECT * FROM Student";


ResultSet rs = stmt.executeQuery(selectSQL);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String dept = rs.getString("dept");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age + ", Department: "
+ dept);
}

System.out.println("Table created and record inserted successfully.");


} catch (SQLException e) {
System.out.println("SQL Error: " + e.getMessage());
}
} catch (ClassNotFoundException e) {
System.out.println("Error: MySQL Connector/J driver not found.");
}
}
}

Output:

You might also like