Is there a built-in way to escape user input in java using the JDBC
? Something similar to the php version mysql_real_escape()
function. What's the best way to validate input?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you mean how do you make sure user input can't be used in SQL injection attacks, the way to do this (and the way all SQL should be written in JDBC) is using Prepared Statements. JDBC will automatically handle any necessary escaping.
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
回答2:
Just to add to the suggestion by @skaffman, PreparedStatements solve the issue for the majority of applications. However, there are some applications where (parts of) SQL statements (as opposed to just parameter values) are taken from user input (for example, a URL parameter containing the ORDER BY clause). Just make sure you sanitize those as well or, better yet, avoid such designs if possible.