Вход на сайт

Просмотр новости

Найдите то, что Вас интересует

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

Дата публикации: 12-01-2022 11:50:00

Instructions on executing SQL queries in Java and preventing SQL injections.
How to execute SQL queries from Java (and prevent SQL injections) appeared first on MariaDB.org


Основное содержимое страницы с новостью.

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:

Enjoyed this post? I can help your team implement similar solutions—contact me to learn more.

Схожие новости

#Наименование новостиТональностьИнформативностьДата публикации
1How to open and close JDBC connections04.7612-01-2022
2New YouTube channel on programming (mostly Java)04.1304-01-2022
3What is a database connection pool?06.114-01-2022
4How to start a web server using Java03.7623-03-2022
5What is MariaDB?07.6621-09-2023
6Why do we need databases and SQL?05.6306-03-2024
7New book (coming) – MariaDB for Developers07.0631-12-2023
8Using AI to modernize a Java project04.1620-07-2026
9Why MariaDB instead of MySQL, PostgreSQL, or MongoDB?05.8525-02-2023
10ChatGPT as a MariaDB database04.6212-01-2023

Классификация: . Схожих патентов: 0. Схожих новостей: 10. Тональность: 0. Информативность: 3.48. Источник: mariadb.org.