在java中避免SQL注入 [英] Avoiding SQL injection in java
本文介绍了在java中避免SQL注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是JavaEE的新手,并试图通过检查数据库来学习创建一个简单的登录页面。以下是代码示例:
I am new to JavaEE and trying to learn to make a simple login page by checking the database. Here is the code sample:
ResultSet result=null;
Statement s = (Statement) con.createStatement();
result=s.executeQuery("select username from Table where ID="+id and " password="+password);
它应该容易受到SQL注入吗?我将通过在ASP.NET中使用参数化查询来执行此操作,如下所示:
It should be vulnerable to SQL injection right? I would do this by using parametrized query in ASP.NET like the following:
SqlConnection con = new SqlConnection();
SqlCommand cmd=new SqlCommand("select username from Table where ID=@id and password=@password",con);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@password", password);
有没有办法在java中使用参数化查询?任何人都可以使用参数化形式的查询来避免SQL注入吗?
Is there any way to use parametrized queries in java like this? Can anyone use that query in parametrized form to avoid SQL injection?
谢谢
推荐答案
是的,您可以使用 PreparedStatement
;例如:
Yes you can do this with PreparedStatement
; for example:
PreparedStatement preparedStatement = con.PreparedStatement(
"SELECT * FROM MY_TABLE WHERE condition1 = ? AND condition2 = ?");
preparedStatement.setString(1,condition1_value);
preparedStatement.setString(2,condition2_value);
ResultSet rs = preparedStatement.executeQuery();
这篇关于在java中避免SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文