简体   繁体   中英

Insert from java into SQL Server appends 'null'

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 , value2 etc) 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 PreparedStatement with parameterized SQL and set parameter values instead.

Benefits:

  • You won't get "null" inserted any more
  • You won't be vulnerable to SQL injection attacks any more (you are now)
  • When inserting non-text data you won't need to worry about problematic conversions (this is particularly relevant for date/time fields)
  • Your code will be clearer, as you'll be separating the code (SQL) from the data (parameter values)
  • Your prepared statement query plan can be cached by the server, so it may perform faster

You should use variable binding in your SQL

http://decipherinfosys.wordpress.com/2007/08/29/bind-variables-usage-parameterized-queries-in-sql-server/

It's easier to check for errors.

In your case you are probably adding null+"foo" so you get nullfoo.

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