JDBC ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-21

Statement, PreparedStatement and ResultSet in JDBC

The query "SELECT id, username FROM users WHERE username = '" + name + "'" works as long as the user types an ordinary name. Type ' OR '1'='1 into the field and it returns the whole users table. The fix is not input validation but a different JDBC interface — PreparedStatement.

Statement, PreparedStatement and ResultSet are interfaces of the java.sql package that a Java program uses to run SQL queries and read their results. Statement runs a ready-made SQL string, PreparedStatement runs a query with ? parameters, and ResultSet holds the rows returned by a SELECT. All three are implemented by the JDBC driver of your database.

1. Statement, PreparedStatement and CallableStatement: Which Interface to Choose

JDBC runs queries through three interfaces that every driver implements: Statement for ready-made SQL strings without parameters, PreparedStatement for queries with parameters and CallableStatement for stored procedures. All three objects are created by a Connection.

Interface How to create Parameters When to use
Statement connection.createStatement() Does not accept any General-purpose database access. Useful for static SQL statements: CREATE TABLE, or a query with no user data
PreparedStatement connection.prepareStatement(sql) Accepts ? parameters at run time Any query that receives values from outside. The default choice in production code
CallableStatement connection.prepareCall("{call ...}") Input and output (OUT) parameters Access to stored procedures in the database

PreparedStatement extends Statement, and CallableStatement extends PreparedStatement, so the methods executeQuery, executeUpdate and addBatch are available in all three. How to get the Connection itself and add the MySQL driver to your project is covered in the lesson JDBC Drivers and Connecting Java to a Database.

2. The Statement Interface: execute, executeUpdate, executeQuery

A Statement object is created by calling connection.createStatement() and runs an SQL string with one of three methods: executeQuery for SELECT (returns a ResultSet), executeUpdate for changing data and table structure (returns a row count), and execute when the type of the query is not known in advance.

Statement statement = connection.createStatement();

Now we can use the statement instance to run SQL queries. The Statement interface has three methods for this, implemented by each JDBC driver:

Method Purpose Returns If you pick the wrong method
ResultSet executeQuery(String sql) SELECT queries A result set to process INSERT in executeQuery throws SQLException (MySQL: Can not issue data manipulation statements with executeQuery())
int executeUpdate(String sql) INSERT, UPDATE, DELETE and DDL (CREATE TABLE, DROP) The number of affected rows; 0 for DDL SELECT in executeUpdate throws SQLException (MySQL: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs)
boolean execute(String sql) When you do not know in advance whether the SQL string is a query or an update true if the first result is a ResultSet; false if it is an update count Works with any statement; you get the result through getResultSet() or getUpdateCount()

The execute method is needed, for example, in a console utility where the user types arbitrary SQL. In ordinary code the type of the query is known, and executeQuery/executeUpdate are easier to read:

boolean isQuery = statement.execute("SELECT id FROM users");
System.out.println(isQuery);                       // true
ResultSet resultSet = statement.getResultSet();

isQuery = statement.execute("UPDATE users SET username = 'ivanov' WHERE id = 100");
System.out.println(isQuery);                       // false
System.out.println(statement.getUpdateCount());    // 0 - there is no row with id = 100

Example 1. Creating a Table with executeUpdate

In all examples of this lesson the connection settings live in the ConnectionData class, and the other classes import them with import static:

package jdbc;

public class ConnectionData {
    public static final String DB = "catalog";
    public static final String URL = "jdbc:mysql://localhost:3306/" + DB;
    public static final String USER = "root";
    public static final String PASSWORD = "admin";
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class CreatingTableExample {
    private static final String CREATE_TABLE_QUERY =
            "CREATE TABLE users "
                    + "(id INT NOT NULL AUTO_INCREMENT,"
                    + " username VARCHAR(50), "
                    + "PRIMARY KEY(id));";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement()) {
            int result = statement.executeUpdate(CREATE_TABLE_QUERY);
            System.out.println("Table created, executeUpdate returned " + result);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

The output on the first run, and on a second run when the table already exists:

Table created, executeUpdate returned 0

Table 'users' already exists

Older examples often use INT(5). The number in parentheses never limited the range of values; it was only a display width, and MySQL 8.0.17 deprecated it. Just write INT. The other MySQL types are described in the lesson MySQL Data Types.

3. The ResultSet Interface and the next() Cursor

ResultSet is the result of a SELECT that you read row by row: the next() method moves the cursor to the next row and returns false when the rows run out, and getInt, getString and the other getXxx methods read the column values of the current row by name or by index.

This interface represents a database result set. It gives the application row-by-row access to the results of queries.

While a query result is being processed, a ResultSet keeps a pointer to the current row. The application moves through the results sequentially until all of them have been processed or the ResultSet is closed.

Main Methods of the ResultSet Interface

Method What it does Notes
boolean next() Moves to the next row. In a newly created result set the cursor stands before the first row, so the first call to next() positions it on the first row Returns true if there is a row and false if there are no more rows to process
getInt("id"), getString(2) and other getXxx Read the value of a column in the current row by name or by index Column indexes start at 1. Reading by name does not break if you reorder the columns in the SELECT
boolean wasNull() Tells whether the last column read was NULL Needed after getInt, getDouble, getBoolean: for NULL they return 0 or false
ResultSetMetaData getMetaData() Information about the result table: the number of columns, their labels and types Useful when the query is not known in advance
void close() Closes the ResultSet immediately Closing the Statement that produced the ResultSet closes the ResultSet automatically

By default a ResultSet has the type TYPE_FORWARD_ONLY and the mode CONCUR_READ_ONLY: you can only read, and only forward. The methods previous(), absolute(int row), beforeFirst() and afterLast() need a scrollable set, while updateRow() and deleteRow() need an updatable one. You request such a set when you create the statement: connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE). On a default set these methods throw SQLException. In practice scrolling is rarely needed: it is simpler to pick the rows you need with WHERE and LIMIT.

Example 2. Reading Rows with ResultSet

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class RetrieveData {
    private static final String SELECT_QUERY = "SELECT * FROM users;";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {

            System.out.printf("%-20s%s%n", "id", "username");
            System.out.println("-------------------------------");
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("username");
                System.out.printf("%-20d%s%n", id, name);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

The output after the table has been filled by Example 3 from the next section:

id                  username
-------------------------------
1                   sidorov
2                   petrov
3                   kozlov

All three resources are declared in one try-with-resources statement and are closed in reverse order: ResultSet, Statement, Connection. Formally the ResultSet would also be closed together with the Statement, but closing it explicitly helps when one Statement runs several queries in a row.

What Happens If You Forget next()

Even if a query returns exactly one row (SELECT COUNT(*) FROM users), the cursor stands before it. Calling resultSet.getInt(1) without a preceding next() throws SQLException, in MySQL with the text Before start of result set. For a single row, write if (resultSet.next()) { ... }.

How to Handle NULL: wasNull and getObject

Primitive methods cannot return NULL: getInt returns 0 and getBoolean returns false. There are two ways to tell a real zero from an empty value: call wasNull() right after reading, or read into a wrapper with getObject(column, Integer.class), which returns null for NULL.

try (Statement statement = connection.createStatement();
     ResultSet resultSet = statement.executeQuery("SELECT NULL AS score")) {
    resultSet.next();
    int score = resultSet.getInt("score");
    System.out.println(score + " " + resultSet.wasNull());

    Integer boxed = resultSet.getObject("score", Integer.class);
    System.out.println(boxed);
}
// Output:
// 0 true
// null

In the opposite direction, to write NULL through a PreparedStatement parameter, call setNull(1, Types.INTEGER).

4. Batch Updates in JDBC

Batch execution sends several data-changing queries to the database in one round trip: queries are collected with addBatch, and executeBatch() runs them and returns an int[] array with the number of affected rows for each query.

To run a set of several update queries, the Statement interface has the following methods:

void addBatch(String sql)
int[] executeBatch()

Batch execution reduces traffic between the client and the DBMS and can significantly improve performance.

Example 3. Batch Insert with Statement

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class InsertBatchData {
    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement()) {

            statement.addBatch("INSERT INTO users (username) VALUES ('sidorov')");
            statement.addBatch("INSERT INTO users (username) VALUES ('petrov')");
            statement.addBatch("INSERT INTO users (username) VALUES ('kozlov')");

            int[] counts = statement.executeBatch();
            System.out.println(Arrays.toString(counts));
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
// Output: [1, 1, 1]

Each element of the array corresponds to a query of the batch, in the order of addBatch. Besides the row count, the driver can return two constants of the Statement interface:

Value in int[] What it means
0, 1, 2, ... The query succeeded and changed that many rows
SUCCESS_NO_INFO (-2) The query succeeded, but the driver does not know how many rows changed. This happens when the driver merged the batch into a single query
EXECUTE_FAILED (-3) The query failed, and the driver went on to run the remaining ones

If one of the queries fails, executeBatch() throws BatchUpdateException (a subclass of SQLException). Its getUpdateCounts() method shows which queries managed to run. The batch is not rolled back on its own: rows from the successful queries stay in the table unless you manage the transaction manually. Transactions will get a lesson of their own.

MySQL has a quirk: by default Connector/J sends the queries of a batch to the server one by one, so the gain from batching is modest. The URL parameter rewriteBatchedStatements=true lets the driver rewrite the batch: for a PreparedStatement with an INSERT it builds a single multi-row INSERT ... VALUES (...), (...), (...). The price is that the array may contain SUCCESS_NO_INFO (-2) instead of the exact row count.

jdbc:mysql://localhost:3306/catalog?rewriteBatchedStatements=true

5. The PreparedStatement Interface

PreparedStatement is an SQL query with ? placeholders whose values are passed separately with setInt, setString and the other setXxx methods. The driver escapes the values itself, so user data cannot change the structure of the query. You create it with connection.prepareStatement(sql).

What makes SQL statements in a PreparedStatement special is that they can have parameters. A parameterized statement contains question marks in its text. For example:

SELECT name FROM persons WHERE age = ?

Before the query runs, the value of each question mark is set explicitly with the setXxx() methods, for example:

ps.setInt(1, 30);

The first argument is the number of the ? in the query, counting from 1. The methods executeQuery(), executeUpdate() and execute() of a PreparedStatement are called without arguments: the query text has already been passed to prepareStatement.

Using PreparedStatement can speed up queries that are executed many times with different parameters: the database parses the query once. How much depends on the driver. In MySQL Connector/J server-side statement preparation is off by default (useServerPrepStmts=false), and the driver simply substitutes the escaped values into the query text. So the main reason to use PreparedStatement is not speed but protection against SQL injection, which the next sections cover.

Example 4. A Query with Parameters via PreparedStatement

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class RetrieveDataPreparedStatement {
    private static final String SELECT_QUERY =
            "SELECT * FROM users WHERE id > ? AND username LIKE ?";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement preparedStatement =
                     connection.prepareStatement(SELECT_QUERY)) {

            preparedStatement.setInt(1, 1);
            preparedStatement.setString(2, "p%");
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    System.out.printf("%-20d%s%n",
                            resultSet.getInt("id"), resultSet.getString("username"));
                }
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
// Output:
// 2                   petrov

The query selects users with an id greater than 1 whose name starts with "p". The ResultSet is opened in a nested try-with-resources because the parameters must be set before executeQuery(). Whether LIKE is case-sensitive is decided by the column collation: with the MySQL 8 default utf8mb4_0900_ai_ci the pattern 'P%' would also find petrov, while with utf8mb4_bin it would not.

Example 5. Batch Insert with PreparedStatement

PreparedStatement has its own addBatch() method without arguments: it adds the current set of parameters to the batch. The query is the same, only the values change.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class InsertDataPreparedStatement {
    private static final String INSERT_QUERY =
            "INSERT INTO users (username) VALUES (?)";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement preparedStatement =
                     connection.prepareStatement(INSERT_QUERY)) {

            preparedStatement.setString(1, "misha");
            preparedStatement.addBatch();

            preparedStatement.setString(1, "grisha");
            preparedStatement.addBatch();
            int[] counts = preparedStatement.executeBatch();
            System.out.println(Arrays.toString(counts));
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
// Output: [1, 1]
// With rewriteBatchedStatements=true in the URL it may be [-2, -2]

After Examples 3 and 5 the table holds five users: sidorov (id 1), petrov (2), kozlov (3), misha (4), grisha (5). The outputs in the following sections are based on this data.

6. SQL Injection and How PreparedStatement Prevents It

SQL injection is an attack in which the user enters not data but a fragment of SQL, and it becomes part of the query. In JDBC it happens when a query is built by concatenating strings in a Statement. The protection is to pass every user-supplied value through ? parameters of a PreparedStatement.

Example 6. A Vulnerable Query Built by String Concatenation

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class SqlInjectionDemo {
    public static void main(String[] args) {
        String name = "' OR '1'='1"; // the user typed this into the "Name" field
        String query = "SELECT id, username FROM users WHERE username = '" + name + "'";
        System.out.println(query);

        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(query)) {
            while (resultSet.next()) {
                System.out.println(resultSet.getInt("id") + " " + resultSet.getString("username"));
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

The output:

SELECT id, username FROM users WHERE username = '' OR '1'='1'
1 sidorov
2 petrov
3 kozlov
4 misha
5 grisha

The quote in the input closed the string literal, and the condition became username = '' OR '1'='1', which is true for every row. If a login check is built the same way, WHERE username = '...' AND password = '...', the same input in the password field gives ... AND password = '' OR '1'='1'. AND is evaluated before OR, so the condition is again true for all rows, and the login succeeds without a password.

The classic input '; DROP TABLE users; -- will not work in MySQL by default: Connector/J does not run several queries in one string unless the URL contains allowMultiQueries=true. But, as you can see above, you do not need a second query to read other people's data or bypass a password.

Example 7. The Same Query with PreparedStatement

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class SafeQueryDemo {
    private static final String SELECT_BY_NAME =
            "SELECT id, username FROM users WHERE username = ?";

    public static void main(String[] args) {
        String name = "' OR '1'='1";

        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement preparedStatement =
                     connection.prepareStatement(SELECT_BY_NAME)) {
            preparedStatement.setString(1, name);
            int found = 0;
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    found++;
                }
            }
            System.out.println("Found: " + found);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
// Output: Found: 0

Now the whole string ' OR '1'='1 is compared with username as an ordinary value, and there is no user with such a name. The structure of the query is fixed in prepareStatement before any data gets into it, and setString cannot change it.

PreparedStatement Does Not Save You from Concatenation

The call connection.prepareStatement("SELECT * FROM users WHERE username = '" + name + "'") is just as vulnerable as Example 6: the injection got into the text before preparation. Only values passed through ? and setXxx are protected.

7. How to Get the id After an INSERT: getGeneratedKeys

To find out the id that the database assigned to a new row through AUTO_INCREMENT, pass the Statement.RETURN_GENERATED_KEYS flag to prepareStatement (or to executeUpdate of a Statement), run the INSERT and read the key from the ResultSet returned by getGeneratedKeys().

Example 8. Getting the Generated id

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class InsertAndGetId {
    private static final String INSERT_QUERY =
            "INSERT INTO users (username) VALUES (?)";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement preparedStatement =
                     connection.prepareStatement(INSERT_QUERY, Statement.RETURN_GENERATED_KEYS)) {

            preparedStatement.setString(1, "ivanov");
            int rows = preparedStatement.executeUpdate();

            try (ResultSet keys = preparedStatement.getGeneratedKeys()) {
                if (keys.next()) {
                    System.out.println("Rows added: " + rows + ", id = " + keys.getInt(1));
                }
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
// Output: Rows added: 1, id = 6

The keys come back as an ordinary ResultSet: one row for each inserted record, so for a batch insert you read them in a while (keys.next()) loop. If you forget the RETURN_GENERATED_KEYS flag, MySQL Connector/J throws SQLException with the message Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS ....

The approach "insert, then run SELECT MAX(id) FROM users" is not acceptable. Between the two queries another thread can insert its own row, and you will get someone else's id. getGeneratedKeys() returns the key of your own insert, because it takes it from the server's response to that INSERT.

8. SQL Types and the getXxx/setXxx Methods

JDBC has a pair of methods for every column type: getXxx of ResultSet for reading and setXxx of PreparedStatement for writing. INT is read with getInt, VARCHAR with getString, money in DECIMAL with getBigDecimal, and dates, since JDBC 4.2 (Java 8), with getObject and a java.time class.

MySQL type Java type Reading Writing
INT int / Integer getInt (returns 0 for NULL) setInt
BIGINT long / Long getLong setLong
VARCHAR, TEXT String getString setString
DECIMAL BigDecimal getBigDecimal setBigDecimal
DATE LocalDate getObject(col, LocalDate.class) setObject(i, localDate)
DATETIME, TIMESTAMP LocalDateTime getObject(col, LocalDateTime.class) setObject(i, localDateTime)
BOOLEAN (in MySQL it is TINYINT(1)) boolean / Boolean getBoolean setBoolean

Do not read an amount stored in DECIMAL with getDouble: double stores decimal fractions approximately, and 0.1 + 0.2 becomes 0.30000000000000004. The methods getDate and getTimestamp also work, but they return the legacy classes java.sql.Date and java.sql.Timestamp, which you then have to convert to java.time anyway. The full table of MySQL types with ranges and Java mappings is in the lesson MySQL Data Types.

9. CallableStatement: Calling a Stored Procedure

CallableStatement calls a stored procedure of the database. The call is written in the JDBC escape syntax {call procedure_name(?, ?)}, input parameters are set with setXxx, and output (OUT) parameters are registered with registerOutParameter and read with getXxx after execution.

A MySQL procedure that returns the number of users through an OUT parameter:

CREATE PROCEDURE count_users(OUT total INT)
BEGIN
    SELECT COUNT(*) INTO total FROM users;
END

In the mysql console client you change the delimiter (DELIMITER //) before this command, otherwise the semicolon inside BEGIN ... END ends the command early. From Java you can run it as is through executeUpdate.

Example 9. Calling a Procedure with CallableStatement

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;

import static jdbc.ConnectionData.URL;
import static jdbc.ConnectionData.USER;
import static jdbc.ConnectionData.PASSWORD;

public class CallProcedure {
    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USER, PASSWORD);
             CallableStatement callableStatement =
                     connection.prepareCall("{call count_users(?)}")) {

            callableStatement.registerOutParameter(1, Types.INTEGER);
            callableStatement.execute();
            System.out.println("Users: " + callableStatement.getInt(1));
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
// Output: Users: 6

In application code stored procedures are less common than plain queries: the logic is kept in Java, where it is easier to test. CallableStatement is more often needed when working with an existing database in which the procedures are already written.

In all examples of this lesson each query is committed to the database immediately: by default a connection works in autocommit mode. To run several queries as one unit you need transactions (commit/rollback). How to move the queries out of main into a separate data access class, keep settings in database.properties and take connections from a HikariCP pool is covered in the lesson DAO Pattern and HikariCP Connection Pool in JDBC.

Frequently Asked Questions

Can I pass a table or column name through ? in a PreparedStatement?

No. The ? parameter substitutes only a value, so SELECT * FROM ? ORDER BY ? will not work: the table name turns into a quoted string and the database returns a syntax error, while ORDER BY ? sorts by a constant. If the user chooses the column name (sorting in a table on a website), check it against a whitelist of allowed names and only then insert it into the query text.

How do I pass a list of values to IN (...) with a PreparedStatement?

One ? accepts one value, so WHERE id IN (?) with the string "1,2,3" will not find what you need. Build as many question marks as the list has elements: String.join(", ", Collections.nCopies(ids.size(), "?")), and then call setInt(i + 1, ids.get(i)) in a loop. Handle an empty list separately: IN () is a syntax error.

Why are parameters and columns in JDBC numbered from 1, not 0?

That is how the JDBC specification defines it, by analogy with SQL, where column positions also start at one. Interviewers ask this question precisely because a Java developer is used to array indexes starting at zero. Calling setString(0, ...) or getString(0) throws SQLException about an index out of range.

If I search with LIKE in a PreparedStatement, do I need to escape anything?

There will be no injection, but the characters % and _ in user input remain LIKE wildcards: a search for the string % returns all records. If you need a literal substring search, replace \ with \\, % with \% and _ with \_ in the value, and then pass it through setString, for example "%" + escaped + "%". An example of a query with LIKE is in the section The PreparedStatement Interface.

Comments

Please log in or register to have a possibility to add comment.