简体   繁体   中英

Dynamic variable in executeUpdate (Java)

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM