Statement and executeQuery
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop's report needs its first five products, so the Java program must ask MySQL for them. Which JDBC object carries the SQL, and which method sends it?
Statement and executeQuery
A Statement is the JDBC object that carries one SQL text from your program to the database. You get one from an open connection with con.createStatement().
Run a SELECT for five products and print each row.
Example 1 · Your first SELECT from Java
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class FirstQueryDemo { public static void main(String[] args) throws SQLException { String url = System.getenv("DB_URL"); // jdbc:mysql://localhost:3306/shoplite String user = System.getenv("DB_USER"); String password = System.getenv("DB_PASSWORD");
try (Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT name, price FROM products ORDER BY product_id LIMIT 5")) {
System.out.println("First five products:"); while (rs.next()) { System.out.println(" " + rs.getString("name") + " - Rs " + rs.getBigDecimal("price")); } } }}First five products: Redmi Note 13 5G - Rs 17999.00 Samsung Galaxy M35 - Rs 19999.00 iPhone 15 128GB - Rs 69900.00 Lenovo IdeaPad Slim 3 - Rs 42990.00 HP Victus 15 Gaming - Rs 64990.00
What this code does
createStatement()gives aStatement, andexecuteQuerysends theSELECTand returns aResultSetwith five rows.while (rs.next())moves to each row in turn;getString("name")andgetBigDecimal("price")read the columns of the current row. The next lesson covers reading in detail.- All three objects are opened in one
try (...), so they are closed in reverse order when the block ends.
A Connection on its own only keeps the line to MySQL open and cannot run SQL, so every query program follows the same steps: open a connection, create a statement, run the SQL, read the results.
Every example in this module reads its settings from the environment variables DB_URL, DB_USER and DB_PASSWORD, set up as in the Connecting to a Database module. The database holds the ShopLite tables and seed data.
Statement and a ResultSet hold resources on the client and the server, just like a Connection. Open all three in the same try (...) so Java closes them for you. The Resource Handling module explains this in depth.Running SELECT name, price FROM products
Two queries run on one Statement: books by price, then a count of active products.
Example 2 · Two queries on one Statement
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class BooksReportDemo { public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
String booksSql = "SELECT name, price FROM products WHERE category_id = 5 ORDER BY price"; try (ResultSet rs = st.executeQuery(booksSql)) { System.out.println("Books, cheapest first:"); while (rs.next()) { System.out.println(" " + rs.getString("name") + " - Rs " + rs.getBigDecimal("price")); } }
String countSql = "SELECT COUNT(*) AS active_products FROM products WHERE is_active = TRUE"; try (ResultSet rs = st.executeQuery(countSql)) { rs.next(); System.out.println("Active products in the shop: " + rs.getInt("active_products")); } } }}Books, cheapest first: Atomic Habits - Rs 399.00 Clean Code - Rs 499.00 The Pragmatic Programmer - Rs 650.00 Active products in the shop: 14
What this code does
- The same
struns two queries. EachResultSetgets its own smalltry, so it is closed before the next query starts. SELECT COUNT(*)always returns exactly one row, so a singlers.next()is enough before readingactive_products.- 14 of the 15 products are active: the USB-C cable has
is_active = FALSEin the seed data.
Write the SQL as a Java String, without the ; at the end: it is the same SQL you typed in the mysql client in the SQL section. One Statement can run many queries, but each new executeQuery closes the ResultSet of the query before it, so finish reading one result before you run the next. Habits that pay off:
- Keep the SQL in a variable such as
booksSql; it is easier to read and to print when something fails. - Use
ORDER BYwhenever the order matters. Without it, MySQL may return rows in any order. - Split long SQL over several lines with
+, and keep a space at the end of each piece.
executeQuery, executeUpdate and execute
An update count is the int that executeUpdate returns: how many rows the SQL changed. execute hands it over through getUpdateCount().
Run a SELECT, an UPDATE and a SQL of unknown kind, and look at what each call returns.
Example 3 · Choosing the execute method
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class ExecuteMethodsDemo { public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
// 1. SELECT -> executeQuery -> a ResultSet try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders WHERE status = 'PLACED'")) { rs.next(); System.out.println("executeQuery: orders waiting to ship = " + rs.getInt(1)); }
// 2. INSERT / UPDATE / DELETE -> executeUpdate -> a row count int rows = st.executeUpdate("UPDATE products SET stock = stock + 5 WHERE sku = 'ACC-M331'"); System.out.println("executeUpdate: rows changed = " + rows);
// 3. execute -> true when the SQL produced a ResultSet, false for a row count boolean hasRows = st.execute("SELECT name FROM categories WHERE parent_id IS NULL ORDER BY name"); System.out.println("execute(SELECT) returned " + hasRows); try (ResultSet rs = st.getResultSet()) { while (rs.next()) { System.out.println(" top-level category: " + rs.getString("name")); } } boolean hasRows2 = st.execute("UPDATE products SET stock = stock - 5 WHERE sku = 'ACC-M331'"); System.out.println("execute(UPDATE) returned " + hasRows2 + ", update count = " + st.getUpdateCount()); } }}executeQuery: orders waiting to ship = 2 executeUpdate: rows changed = 1 execute(SELECT) returned true top-level category: Books top-level category: Electronics top-level category: Fashion top-level category: Home & Kitchen execute(UPDATE) returned false, update count = 1
What this code does
executeQuerygives rows andexecuteUpdategives a count:1row changed, because one product has the SKUACC-M331.executereturnstruefor theSELECT, so the program reads the rows withgetResultSet(). For theUPDATEit returnsfalse, andgetUpdateCount()gives the count.- The second
UPDATEtakes the 5 units back out, so the data is unchanged after the run.
Example 4 · Wrong method: the real errors
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;
public class WrongMethodDemo { public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
try { st.executeQuery("UPDATE products SET stock = stock + 1 WHERE sku = 'BK-CLEAN'"); } catch (SQLException e) { System.out.println("executeQuery with UPDATE:"); System.out.println(" " + e.getMessage()); }
try { st.executeUpdate("SELECT name FROM products"); } catch (SQLException e) { System.out.println("executeUpdate with SELECT:"); System.out.println(" " + e.getMessage()); } } }}executeQuery with UPDATE: Statement.executeQuery() cannot issue statements that do not produce result sets. executeUpdate with SELECT: Statement.executeUpdate() or Statement.executeLargeUpdate() cannot issue statements that produce result sets.
What this code does
- Both mistakes throw
SQLExceptionfrom the driver. It checks the kind of SQL before sending it, so theUPDATEnever runs. - The messages name the method you called, which tells you straight away which call to change.
Use execute only when your program truly does not know the kind of SQL in advance, such as a tool that runs SQL typed by an admin. Call the wrong method and the MySQL driver stops you before anything runs on the server; the next example shows the messages.
Predict the output
What does each call return?
Pick what is printed. One product has the SKU ACC-M331.
Round 1 of 2
An UPDATE runs through executeUpdate.
SQL syntax errors from Java
SQLSyntaxErrorException is thrown when MySQL cannot understand or check your SQL: a misspelt keyword, or a column or table that does not exist.
Four queries run, three with a typo, and the program prints MySQL's own message for each.
Example 5 · Reading SQL errors
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;
public class SqlErrorsDemo { static void tryQuery(Statement st, String sql) { try (ResultSet rs = st.executeQuery(sql)) { System.out.println("OK: " + sql); } catch (SQLException e) { System.out.println("FAILED: " + sql); System.out.println(" " + e.getClass().getSimpleName() + ": " + e.getMessage()); } }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
List<String> queries = List.of( "SELECT name, prise FROM products", // misspelled column "SELECT name, price FROM product", // table name is products "SELECT name, price FORM products", // FROM typed as FORM "SELECT name, price FROM products"); for (String sql : queries) { tryQuery(st, sql); } } }}FAILED: SELECT name, prise FROM products SQLSyntaxErrorException: Unknown column 'prise' in 'field list' FAILED: SELECT name, price FROM product SQLSyntaxErrorException: Table 'shoplite.product' doesn't exist FAILED: SELECT name, price FORM products SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'products' at line 1 OK: SELECT name, price FROM products
What this code does
tryQuerycatches the exception and prints the failing SQL, then the exception type and MySQL's message.- For
FORM, MySQL readFORMas a column alias (a new name forprice) and got stuck atproducts. That is why the message points at'products', just after the real typo. - Output from a real run. In your run the database name is the one in your
DB_URL.
Java compiles your program happily, because to Java the SQL is just text inside a String; the mistake shows up only when the program runs. Unknown column 'prise' in 'field list' names the bad column, and Table 'shoplite.product' doesn't exist names the database and the table. For a broken sentence MySQL says near '...': the quoted text is where it got confused, which is often just after the real mistake.
Always print or log the failing SQL together with the message. With only the message you have to hunt through the code for the query that failed.
Fix the error
Fix the SQL typo
Read the real MySQL error, then pick the line that fixes it.
Round 1 of 3
The query names a column that is not in the table.
Error
Unknown column 'prise' in 'field list'
mysql client first. When it works there, copy it into Java. It saves many edit-compile-run rounds.Statement is only for fixed SQL
Fixed SQL is SQL whose text is written completely in your code, such as "SELECT name FROM categories ORDER BY name", with no user text glued in.
Search a category by gluing its name into the SQL with +, and see what the database receives.
Example 6 · Why text glued into SQL breaks
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class BuiltSqlBreaksDemo { // Shown only to explain the problem: never build SQL from text like this static void findCategory(Statement st, String name) { String sql = "SELECT category_id, name FROM categories WHERE name = '" + name + "'"; System.out.println("SQL sent: " + sql); try (ResultSet rs = st.executeQuery(sql)) { if (rs.next()) { System.out.println(" found id " + rs.getInt("category_id")); } else { System.out.println(" no such category"); } } catch (SQLException e) { System.out.println(" " + e.getMessage()); } }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) { findCategory(st, "Books"); findCategory(st, "Children's Books"); } }}SQL sent: SELECT category_id, name FROM categories WHERE name = 'Books' found id 5 SQL sent: SELECT category_id, name FROM categories WHERE name = 'Children's Books' You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Books'' at line 1
What this code does
- With
Booksthe SQL is fine. WithChildren's Books, the'inside the name closes the text value early, and MySQL sees the broken tails Books''. - The method prints the SQL it sends. That is the quickest way to see what went wrong with built SQL, and it shows why user text must never be glued in.
Statement is safe and simple for fixed SQL. The trouble starts when you glue a value from the user into the SQL text with +. Worse than a broken query, a user can type SQL on purpose and it will run as part of your query: this attack is called SQL injection.
So in this module Statement runs only fixed SQL, or SQL with Java numbers (int, BigDecimal), which cannot contain quotes. Any text that comes from a user waits for PreparedStatement, which passes values as data, never as SQL. The Prepared Statements and SQL Injection module covers it.
Find the bug
Which line glues in user text?
Tap the line that can break or be attacked.
A shopper types a category name into a search box.
Round 1 of 2Next step
Check your understanding
12 quick questions