Support Online
Skip to main content

SQL Injection and Secure Database Access in Java Applications

💡 What Will You Learn in This Guide?

This guide explains in depth the concept of SQL Injection, one of the most critical security vulnerabilities in the software world.
You will see how the attack occurs through a Java web application example, and then you will learn how to completely close this vulnerability using PreparedStatement.
We will also take a step-by-step review of best practices that comply with secure coding standards.

🧠 What is SQL Injection?

SQL Injection is a vulnerability that occurs by injecting malicious SQL statements into user input.
This vulnerability can be seen in any application that uses relational database systems (MySQL, Oracle, PostgreSQL, etc.).

An attacker manipulates the query by writing malicious code in input or form fields.
The result is unauthorized access to the database, data theft or data manipulation.

🎯 Possible Effects

  • Unauthorized access to user data
  • Changing or deleting database records
  • Performance decrease or complete system failure
  • Taking control of the server

🧩 How Does SQL Injection Perform?

In the example below, the ID value from the user is added directly to the query:

// ⚠️ Güvensiz sorgu örneği
String userId = request.getParameter("userId");
String query = "SELECT * FROM tbluser WHERE userId = " + userId;

🔹 Normal Input

Input:

132

Query:

SELECT * FROM tbluser WHERE userId = 132

✅ Only the user with ID 132 returns.

🔹 Attacker Input Input:

2 OR 1=1

Query:

SELECT * FROM tbluser WHERE userId = 2 OR 1=1

❌ Since 1=1 is always true, all user data is listed.

🧠 Types of SQL Injection

GenreDescription
Boolean BasedManipulates the result of the query with logical expressions (OR 1=1).
UNION BasedData from other tables is combined with the expression UNION.
Time BasedWith functions such as SLEEP(), the query is delayed and the server response is measured.
Error BasedError messages are triggered with incorrect syntax and the system structure is learned.

⚠️ Unsafe Java Code Example

// ⚠️ SQL Injection’a açık kod
String query = "SELECT * FROM tbluser WHERE username='" + username + "' AND password='" + password + "'";
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user", "root", "genixnode_sifre");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

Since the user input in this query is inserted directly into the SQL, it is completely open to attack.

🔥 Attack Scenario

If the attacker enters ' OR '1'='1 in the password field:

SELECT * FROM tbluser WHERE username='dummy' AND password='' OR '1'='1'

➡️ In this case, the system allows unauthorized access as '1=1' will always return true.

✅ Preventing SQL Injection: PreparedStatement

The most effective protection method against SQL Injection is to use Prepared Statements. With this method, the query structure is defined in advance, and user input is processed completely separate from the query.

// ✅ Güvenli sorgu örneği
String query = "SELECT * FROM tbluser WHERE username=? AND password=?";
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user", "root", "genixnode_sifre");
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();

In this example? signs are positional parameters. The data from the user is not added to the query, it is only bound. Thus, expressions like OR 1=1 are treated as data, not code.

🧰 Security Best Practices

Use Prepared Statements.

Perform input validation: add length, type and format checks.

Keep database user permissions to a minimum.

Hide error messages, do not reflect system information outside.

Abstract the data layer with tools like ORM (Hibernate, JPA).

Detect dangerous queries early by performing code reviews.


💬 Frequently Asked Questions (FAQ)

  1. Does PreparedStatement completely prevent SQL Injection?

Yes, when used correctly it almost completely blocks classic SQL Injection attacks.

  1. Why is Statement still used?

Preferred for queries that are static or do not involve user input; otherwise it is not recommended.

  1. Is using Hibernate enough?

Hibernate is safe most of the time, but be careful with createNativeQuery() or manual queries.

  1. How does PreparedStatement perform?

It is cached on first run; Works faster on repetitive queries.

  1. What are SQL Injection testing tools?

You can use security testing tools such as SQLMap, Burp Suite, OWASP ZAP.

🏁 Result

SQL Injection is a vulnerability that can compromise the entire system security with a simple mistake. You can eliminate this risk and manage your data safely by using PreparedStatement in your Java applications.

☁️ Increase your database security by testing your secure JDBC applications on the GenixNode platform.