0

Keeping prepared statements aside, Alternatively I want to "stay safe" from sql injection in java...

I thought of doing this (a htmlentity conversion) ?

suspectedInputvariable.replace("'","'")
                      .replace(";","ŧ")
                      .replace("\"",""");

is suspectedInputvariable now safe to be embedded with a sql query?

3
  • why would you want to keep prepared statements aside? Commented Mar 24, 2012 at 11:50
  • I wrote a separate class where i just issue a query and nothing more arguments Commented Mar 24, 2012 at 11:53
  • 2
    @everlasto: That's not a reason not to use a prepared statement. Commented Mar 24, 2012 at 12:02

2 Answers 2

3

First, why would you want to do such a thing? The driver knows how to safely treat strings. Just use a PreparedStatement.

Second, you have to escape \ and some other characters, too. If you handle all the characters listed here your code should be reasonably safe with MySQL: http://dev.mysql.com/doc/refman/4.1/en/mysql-real-escape-string.html The list of characters for other databases may differ.

Sign up to request clarification or add additional context in comments.

5 Comments

eager to know if possible w/o ppd stt .. and there are ways to escape backslashes too
Of course it is possible, but it's easy to get it wrong. For example PHP has mysql_escape_string, that mostly works, until someone figured out that it can be fooled by unicode strings. Now they recommend mysql_real_escape_string. The risk of having your database open to all imaginable queries is just too scary.
Thanks Joni, for now just have to escape only \x00, \n, \r, \, ', " and \x1a until someone figures out the next hack ;) .. if i could find something than ppd stt, it will drastically reduce my time.. tats y im interested..
You could create the prepared statement once and hold it in a cache. They are meant to be reused with different parameters.. or does the sql itself vary? (list of fields, tables, where-conditions..)
@everlasto: it's hard to even imagine a scenario where prepared statements, correctly used, cause any significant performance problems.
2

is suspectedInputvariable now safe to be embedded with a sql query?

Probably not. There are all kinds of little-known features in various SQL dialects that could be used to circumvent this blacklist.

Just use prepared statements. Period.

1 Comment

so ppd stts seems to be the final destination :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.