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. What 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.
2. Why 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.
3. Real-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.
4. Syntax
javaStatement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM students");
5. Example Program
javaimport 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.)
6. Key Points to Remember
Statementis 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.