← Back to Chapters

JDBC Statement

☕ JDBC Statement

? Quick Overview

In Advance Java, the Statement interface is used to send static SQL queries to the database. It is part of the java.sql package and works with JDBC to execute SELECT, INSERT, UPDATE, and DELETE queries.

? Key Concepts

  • Statement is created using a Connection object
  • Used for simple and static SQL queries
  • Executes SQL using methods like executeQuery() and executeUpdate()
  • Vulnerable to SQL Injection

? Syntax / Theory

The general flow of using a JDBC Statement:

  1. Load JDBC Driver
  2. Create Database Connection
  3. Create Statement object
  4. Execute SQL Query
  5. Process Result
  6. Close Connection

? Code Example(s)

? View Code Example
// Step 1: Import required packages
import java.sql.*;

// Step 2: Main class
public class StatementExample {
public static void main(String[] args) {

// Step 3: Database credentials
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "";

try {
// Step 4: Establish connection
Connection con = DriverManager.getConnection(url, user, password);

// Step 5: Create Statement
Statement stmt = con.createStatement();

// Step 6: Execute SELECT query
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

// Step 7: Process result set
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

// Step 8: Close connection
con.close();

} catch (Exception e) {
System.out.println(e);
}
}
}

? Interactive Simulator: How it Works

Click "Next Step" to visualize how Java communicates with the Database.

 

Java App
 
?️
MySQL DB
> Ready to start...

? Live Output / Explanation

Output

The program connects to the database, executes a SQL query, and prints all records from the students table row by row.

✅ Tips & Best Practices

  • Always close database connections to avoid memory leaks
  • Use PreparedStatement instead of Statement for dynamic queries
  • Handle exceptions properly using try-catch
  • Avoid hardcoding database credentials in production

? Try It Yourself

  • Create a table and fetch records using Statement
  • Execute an INSERT query using executeUpdate()
  • Modify the program to display data in formatted output