0
0
JavaHow-ToBeginner · 2 min read

How to Execute SQL Query in Java with JDBC Example

To execute an SQL query in Java, use Connection to connect to the database, create a Statement or PreparedStatement, then call executeQuery(sql) for SELECT or executeUpdate(sql) for INSERT/UPDATE/DELETE.
📋

Examples

InputSELECT * FROM users
OutputPrints all rows from the users table
InputINSERT INTO users (name, age) VALUES ('Alice', 30)
OutputInserts a new user named Alice with age 30
InputUPDATE users SET age = 31 WHERE name = 'Alice'
OutputUpdates Alice's age to 31
🧠

How to Think About It

First, connect to the database using a Connection. Then create a Statement object to send SQL commands. Use executeQuery for queries that return data, and executeUpdate for commands that change data. Finally, process the results or check the update count.
📐

Algorithm

1
Establish a database connection using <code>DriverManager.getConnection</code>.
2
Create a <code>Statement</code> or <code>PreparedStatement</code> object from the connection.
3
Execute the SQL query using <code>executeQuery</code> for SELECT or <code>executeUpdate</code> for INSERT/UPDATE/DELETE.
4
If SELECT, process the <code>ResultSet</code> returned to read data.
5
Close the <code>ResultSet</code>, <code>Statement</code>, and <code>Connection</code> to free resources.
💻

Code

java
import java.sql.*;

public class ExecuteSQL {
    public static void main(String[] args) {
        String url = "jdbc:h2:mem:testdb";
        String sql = "SELECT 1 AS number";
        try (Connection conn = DriverManager.getConnection(url);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                System.out.println("Number: " + rs.getInt("number"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Output
Number: 1
🔍

Dry Run

Let's trace the example SELECT query through the code

1

Connect to database

Connection established to jdbc:h2:mem:testdb

2

Create statement

Statement object created from connection

3

Execute query

SQL 'SELECT 1 AS number' sent to database

4

Process result

ResultSet contains one row with number=1

5

Print output

Prints 'Number: 1'

StepActionValue
1Connectjdbc:h2:mem:testdb
2Create StatementStatement object
3Execute QuerySELECT 1 AS number
4Read ResultSetnumber=1
5PrintNumber: 1
💡

Why This Works

Step 1: Connect to database

The DriverManager.getConnection method opens a connection to the database URL.

Step 2: Create statement

A Statement object lets you send SQL commands to the database.

Step 3: Execute query

executeQuery runs the SQL and returns a ResultSet for reading data.

Step 4: Process results

You loop through the ResultSet to get each row's data.

🔄

Alternative Approaches

Using PreparedStatement
java
import java.sql.*;

public class ExecuteSQLPrepared {
    public static void main(String[] args) {
        String url = "jdbc:h2:mem:testdb";
        String sql = "SELECT ? AS number";
        try (Connection conn = DriverManager.getConnection(url);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, 1);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    System.out.println("Number: " + rs.getInt("number"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
PreparedStatement helps prevent SQL injection and allows parameterized queries.
Using executeUpdate for data change
java
import java.sql.*;

public class ExecuteUpdateSQL {
    public static void main(String[] args) {
        String url = "jdbc:h2:mem:testdb";
        String create = "CREATE TABLE test(id INT)";
        String insert = "INSERT INTO test VALUES(1)";
        try (Connection conn = DriverManager.getConnection(url);
             Statement stmt = conn.createStatement()) {
            stmt.execute(create);
            int rows = stmt.executeUpdate(insert);
            System.out.println("Rows inserted: " + rows);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Use executeUpdate for INSERT, UPDATE, DELETE; it returns affected row count.

Complexity: O(n) time, O(n) space

Time Complexity

The time depends on the number of rows returned or affected by the query, so it is O(n) where n is the number of rows processed.

Space Complexity

Space is O(n) for storing the ResultSet data in memory while processing rows.

Which Approach is Fastest?

Using PreparedStatement is slightly faster for repeated queries and safer, while Statement is simpler for one-off queries.

ApproachTimeSpaceBest For
Statement.executeQueryO(n)O(n)Simple SELECT queries
PreparedStatement.executeQueryO(n)O(n)Parameterized and repeated queries
Statement.executeUpdateO(1)O(1)Data modification commands
💡
Always close your Connection, Statement, and ResultSet to avoid resource leaks.
⚠️
Forgetting to call executeQuery for SELECT or using executeUpdate incorrectly causes errors.