Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape user-supplied parameters with a SQL query?

Trying to get started with JDBC (using Jetty + MySQL). I'm not sure how to escape user-supplied parameters in a SQL statement. Example:

String username = getDangerousValueFromUser();
Statement stmt = conn.createStatement();
stmt.execute("some statement where username = '" + username + "'"));

How do we escape "username" before use with a statement?

like image 778
user291701 Avatar asked Feb 10 '11 06:02

user291701


People also ask

How do I escape a SQL statement?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.

What is the best defense against SQL injection?

You should always use parameterized statements where available, they are your number one protection against SQL injection. You can see more examples of parameterized statements in various languages in the code samples below.

What is parameterised query in SQL?

A parameterized query (also known as a prepared statement) is a means of pre-compiling a SQL statement so that all you need to supply are the "parameters" (think "variables") that need to be inserted into the statement for it to be executed. It's commonly used as a means of preventing SQL injection attacks.

Do parameterized queries prevent SQL injection?

Correct usage of parameterized queries provides very strong, but not impenetrable, protection against SQL injection attacks.


1 Answers

Use Prepared statement.

for example :

con.prepareStatement("update Orders set pname = ? where Prod_Id = ?");
pstmt.setInt(2, 100);
pstmt.setString(1, "Bob");
pstmt.executeUpdate();

It will prevent raw SQL injection

If you want to escape sql string then check for StringEscapeUtils.escapeSql(). Note that that this method was deprecated in Commons Lang 3.

Also See

  • does-using-preparedstatement-mean-there-will-not-be-any-sql-injection
like image 67
jmj Avatar answered Oct 24 '22 05:10

jmj