Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the preparedStatement avoid SQL injection? [duplicate]

I have read and tried to inject vulnerable sql queries to my application. It is not safe enough. I am simply using the Statement Connection for database validations and other insertion operations.

Is the preparedStatements safe? and moreover will there be any problem with this statement too?

like image 384
Mohamed Saligh Avatar asked Dec 02 '10 08:12

Mohamed Saligh


People also ask

Does PreparedStatement prevent SQL injection?

What are Prepared Statements? A prepared statement is a parameterized and reusable SQL query which forces the developer to write the SQL command and the user-provided data separately. The SQL command is executed safely, preventing SQL Injection vulnerabilities.

What is the disadvantage of PreparedStatement?

Following are the limitations of prepared statements: Since a PreparedStatement object represents only one SQL statement at a time, we can execute only one statement by one prepared statement object. To prevent injection attacks it does not allow more than one value to a place holder.

What benefit does the PreparedStatement provide?

PreparedStatement prevents SQL Injection attacks in Java In an SQL Injection attack, malicious users pass SQL meta-data combined with input which allowed them to execute SQL queries of their choice, If not validated or prevented before sending a query to the database.

Which query we avoid in SQL injection?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.


2 Answers

Using string concatenation for constructing your query from arbitrary input will not make PreparedStatement safe. Take a look at this example:

preparedStatement = "SELECT * FROM users WHERE name = '" + userName + "';"; 

If somebody puts

' or '1'='1 

as userName, your PreparedStatement will be vulnerable to SQL injection, since that query will be executed on database as

SELECT * FROM users WHERE name = '' OR '1'='1'; 

So, if you use

preparedStatement = "SELECT * FROM users WHERE name = ?"; preparedStatement.setString(1, userName); 

you will be safe.

Some of this code taken from this Wikipedia article.

like image 183
darioo Avatar answered Sep 19 '22 06:09

darioo


The prepared statement, if used properly, does protect against SQL injection. But please post a code example to your question, so we can see if you are using it properly.

like image 42
pts Avatar answered Sep 18 '22 06:09

pts