Skip to content
CampusEduX

File Handling & JDBC · Lesson 113 of 150

Statement

Statement is a JDBC interface used to send simple SQL queries to a database and execute them, without any parameters that change between executions.

1 min read

01What is Statement?

Statement is a JDBC interface used to send simple SQL queries to a database and execute them, without any parameters that change between executions.

02Why is it used?

It's the most basic way to run SQL commands from Java — useful for simple, fixed queries where the SQL text itself doesn't need to change based on outside input.

03Real-Life Example

Think of reading out a fixed, pre-written announcement exactly as written, every single time, without changing any part of it based on the audience. Statement works well for this kind of fixed, unchanging instruction.

04Syntax

java
Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM students");

05Example Program

java
import java.sql.*; public class StatementDemo { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/schooldb", "root", "password" ); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT name FROM students"); while (rs.next()) { System.out.println(rs.getString("name")); } conn.close(); } }

Output:

Aditi
Rohan
Sneha

(Actual output depends on the real data present in the students table.)

06Key Points to Remember

  • Statement is suitable only for fixed queries; it's not safe for queries built directly from user input.
  • Directly inserting user input into a Statement's SQL text can lead to SQL injection security risks.
  • PreparedStatement (next topic) is the safer, recommended choice when input values are involved.