Skip to main content

How to execute SQL queries from Java (and prevent SQL injections)

·231 words·2 mins
Programming Databases
Alejandro Duarte
Author
Alejandro Duarte
Alejandro Duarte is a Software Engineer, published author, and award winner. He currently works for MariaDB plc as a Developer Relations Engineer. Starting his coding journey at 13 with BASIC on a rudimentary black screen, Alejandro quickly transitioned to C, C++, and Java during his academic years at the National University of Colombia. Relocating first to the UK and then to Finland, Alejandro deepened his involvement in the open-source community. He’s a recognized figure in Java circles, credited with articles and videos amassing millions of views, and presentations at international events.

To run SQL queries in Java, you need a Connection object. See the previous post to learn how to get one. With this object, simply build a new PreparedStatement, set the query parameters (NEVER USE STRING CONCATENATION OR THE APP WILL BE VULNERABLE TO SQL INJECTION ATTACKS, sorry for yelling), and run the SQL statement. Depending on whether you are modifying data or not, you call different methods to send the statement to the database.

Reading data:

try (PreparedStatement statement = connection.prepareStatement("""
            SELECT column1, column2
            FROM table_name
        """)) {
    ResultSet resultSet = statement.**executeQuery**();
    while (resultSet.next()) {
        String val1 = resultSet.getString(1); // by column index
        int val2 = resultSet.getInt("column2"); // by column name
        // ... use val1 and val2 ...
    }
}

Inserting, updating, or deleting data:

try (PreparedStatement statement = connection.prepareStatement("""
            INSERT INTO table_name(column1, column2)
            VALUES (?, ?)
        """)) {
    statement.**setString**(1, someString);
    statement.**setInt**(2, someInteger);
    int rowsInserted = statement.**executeUpdate**();
}

The setString(int, String) and setInt(int, int) methods escape special characters so attackers cannot use a malicious string that contains SQL code to perform an injection attack. There are similar methods for other Java types.

See JDBC Tutorial Part 2: Running SQL Queries, for a more detailed tutorial or watch me coding an example Java application from scratch using JDBC and a MariaDB database:

If you liked this post, consider  following me on Twitter and subscribing to  Programming Brain on Youtube. Happy coding!

Related

How to open and close JDBC connections
·153 words·1 min
Programming Databases
To open and close database connections in Java, get a JDBC driver for your database.
Testing MariaDB ColumnStore performance
·1288 words·7 mins
SQL Databases
MariaDB’s ColumnStore is an engine that stores data in a columnar fashion.
Using Vaadin web components in HTML documents without frameworks
·525 words·3 mins
Programming Vaadin UI
Vaadin is a development platform for building web applications in Java.