java sql注入,在java中避免SQL注入

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);

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);

Is there any way to use parametrized queries in java like this? Can anyone use that query in parametrized form to avoid SQL injection?

Thanks

解决方案

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();

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); 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); Is there any way to use parametrized queries in java like this? Can anyone use that query in parametrized form to avoid SQL injection? Thanks 解决方案 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();
经验分享 程序员 微信小程序 职场和发展