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.
Connection objectexecuteQuery() and executeUpdate()The general flow of using a JDBC Statement:
// 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);
}
}
}
Click "Next Step" to visualize how Java communicates with the Database.
The program connects to the database, executes a SQL query, and prints all records from the students table row by row.
PreparedStatement instead of Statement for dynamic queriesINSERT query using executeUpdate()