Skip to content
C

JDBC Programs

Practicing JDBC operations end-to-end helps connect the concepts (Connection, Statement, ResultSet) covered earlier into a complete, working flow.


Why practice these?

Practicing JDBC operations end-to-end helps connect the concepts (Connection, Statement, ResultSet) covered earlier into a complete, working flow.

Program 1: Insert and Retrieve a Record

java
import java.sql.*; public class JdbcPractice { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/schooldb"; try (Connection conn = DriverManager.getConnection(url, "root", "password")) { PreparedStatement insert = conn.prepareStatement( "INSERT INTO students (name, age) VALUES (?, ?)" ); insert.setString(1, "Meera"); insert.setInt(2, 21); insert.executeUpdate(); PreparedStatement select = conn.prepareStatement( "SELECT name, age FROM students WHERE name = ?" ); select.setString(1, "Meera"); ResultSet rs = select.executeQuery(); while (rs.next()) { System.out.println(rs.getString("name") + " - " + rs.getInt("age")); } } catch (SQLException e) { System.out.println("Database error: " + e.getMessage()); } } }

Output:

Meera - 21

(Requires a real, running database with a matching table for actual execution.)

Key Points to Remember

  • Practicing a complete insert-then-read flow ties together Connection, PreparedStatement, and ResultSet in one working example.
  • Always wrap JDBC code in try-catch (or try-with-resources) to handle potential SQLExceptions gracefully.
  • Testing JDBC code requires an actual running database instance with matching table structures.