I’m trying to insert values into a SQL database from within Java. This works fine, except for some of the values. Eg, when I insert “foo” it appends null at the start so it becomes “nullfoo”. If I insert the same statement in SQL Server Management Studio this doesn’t happen.
To be sure: I print the string before inserting it and it reads “foo”.
My insert code:
statement.execute("INSERT INTO " + settings.getProperty("table") + " VALUES ('" + value1+ "', '" + value2 + "', '" + value3 + "')");
You’re concatenating values into the SQL statement. If any of those references (
value1,value2etc) are null, then those will be converted into the string “null” as part of concatenation.The correct fix for this is not to change the way you’re doing validation – it’s to stop putting the values into the SQL statement itself. Use
PreparedStatementwith parameterized SQL and set parameter values instead.Benefits: