This tutorial aims to guide you through executing SQL queries using JDBC's Statement interface. We'll cover the basics, including how to create a Statement object and use it to execute various types of SQL queries.
By the end of this tutorial, you will be able to:
You should have a basic understanding of Java and SQL before starting this tutorial.
To execute SQL queries, we first need to create a Statement object. This can be done using the createStatement()
method of the Connection object.
Statement statement = connection.createStatement();
With the statement object, you can now execute SQL queries. There are three methods you can use:
executeQuery()
: For SELECT queries which return a ResultSet.executeUpdate()
: For INSERT, UPDATE, DELETE, or DDL statements.execute()
: For any type of SQL statement.// Create a Statement object
Statement statement = connection.createStatement();
// Execute SELECT query
ResultSet resultSet = statement.executeQuery("SELECT * FROM students");
// Fetch each row from the ResultSet
while (resultSet.next()) {
System.out.println(resultSet.getInt("id") + ", " + resultSet.getString("name"));
}
This code will print out all students in the "students" table.
// Create a Statement object
Statement statement = connection.createStatement();
// Execute INSERT query
int rowsAffected = statement.executeUpdate("INSERT INTO students VALUES (1, 'John Doe')");
// Print out the number of inserted rows
System.out.println("Inserted " + rowsAffected + " row(s).");
This code will insert a new student into the "students" table and print out the number of inserted rows.
In this tutorial, we've learned how to create a Statement object using the JDBC's Statement interface and execute various types of SQL queries. This is a fundamental skill for interacting with databases in Java.
Write a Java program to update a student's name in the "students" table.
Write a Java program to delete a student from the "students" table.
Write a Java program to select all students from the "students" table and print out their names.
For further practice, try to execute more complex SQL queries and handle the results in your Java program.
// Exercise 1
Statement statement = connection.createStatement();
int rowsAffected = statement.executeUpdate("UPDATE students SET name = 'Jane Doe' WHERE id = 1");
System.out.println("Updated " + rowsAffected + " row(s).");
// Exercise 2
Statement statement = connection.createStatement();
int rowsAffected = statement.executeUpdate("DELETE FROM students WHERE id = 1");
System.out.println("Deleted " + rowsAffected + " row(s).");
// Exercise 3
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT name FROM students");
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
Remember to replace the SQL queries with your own ones, and ensure that your database connection works properly. Good luck!