1

I have the following connection, statement and executeUpdate

Connection con = DBConnPool.getInstance().getConnection();
Statement stmt = con.createStatement();

//String str1 = "update node set compareflag=0, personalid=NULL where ipaddress='192.168.150.213'";

String str1 = "update node set compareflag=0, personalid=NULL where ipaddress='var3.getIpAddress()'";
                            stmt.executeUpdate(str1);

The commented out String line works perfectly, the other one ignores the value returned by var3.getIpAddress() even though that variable does contain the correct data which I use in other areas of my code.

Do I have to create a separate variable first and then equate it to var3.getIpAddress() ?

Any thoughts appreciated, it's probably insufficient " or " in the wrong place.

1
  • Start here. You can't invoke Java methods from a portion of String literal. Commented Oct 8, 2018 at 15:50

2 Answers 2

3

Prefer a PreparedStatement with a bind parameter. Dynamically building a query leaves you vulnerable to SQL Injection attacks. PreparedStatement (when used correctly) is immune to SQL Injection. It also makes the code easier to read and reason about. For example,

Connection con = DBConnPool.getInstance().getConnection();
String qry = "update node set compareflag=0, personalid=NULL where ipaddress=?";
PreparedStatement stmt = con.prepareStatement(qry);
stmt.setString(1, var3.getIpAddress());
stmt.executeUpdate();
Sign up to request clarification or add additional context in comments.

3 Comments

OK but you may consider using variables also for the other columns being updated.
Thanks for all replies, much appreciated.
@RobertKock There is no reason to do that if those values are fixed.
3

You should use PreparedStatement to set parameter for safe.

PreparedStatement pstmt = con.prepareStatement("update node set compareflag=0, personalid=NULL where ipaddress=?");
pstmt.setString(1,var3.getIpAddress());
pstmt.executeUpdate();

3 Comments

OK but you may consider using variables also for the other columns being updated.
The last line is incorrect. pstmt.executeUpdate(str1); invokes the method from Statement.executeUpdate(String) (where str1 is a query and the previously bound query and parameter are ignored).
@ElliottFrisch Even stronger executeUpdate(String) on a PreparedStatement should always throw a SQLException, that is required by the JDBC specification.

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.