Hi everyone, I need some help. I have a program that creates a window with JTexboxes on it and a button. The user is to fill in the textboxes and press the button. When this occurs the program is to retreive the information from the textboxes and then insert it into a database. I used getText() to get the information from the textboxes. That works fine. But when i press the button to send it to the database it gives me an error "NumberFormatException" and then the contents of the textbox in question. Everything seems to be fine. I get the information as a String pass it to the method as a string. Then when i send it to the database I use parseInt() to change it to an Integer because the format of the database column is int(11). I don't know why it is giving me this error. Another funny thing that is happening is that it gives me the error only when i fill in the next following textbox which is also an Integer. Here is the code:
I allways create the sql-statement as separate String, so I can easily debug it, paste it to an editor and try to execute it with other methods than my application:
Most syntax-errors are very easy to find in the printed statement, without all that masking javacode.
If 'age' is an int, you should insert it by
Some noise in your code is the copying of parameters to local values, and why do you cast a String to a String?
A much more secure way in two meanings is, to use prepared statements (see the javadocs for details). 1.) You don't need to mask Strings with + ",'" and + "', " - more secure for the developer. 2.) It's much more secure at runtime. Imagine names containing ' like O'Reilly. Bad guys (and girls) use this trap for sql-injection-attacks.
Instead of building the SQL statement yourself by concatenating SQL fragments and parameters, use java.sql.PreparedStatement. You write an SQL statement with question marks in the place of the parameters and use the set...() methods of PreparedStatement to set the values. The JDBC driver will take care of adding quotes or other conversions necessary for the database.
I agree with the previous two posts: use PreparedStatement. It also has another benefit: if you are inserting multiple rows, it's more efficient, because it's precompiled. Even if you only insert one row at a time, prepared statements are often pooled, in the same way connections are pooled, so you still get the performance benefits.