wood burning stoves 2.0*
The moose likes JDBC and the fly likes Fetching values from the database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Fetching values from the database" Watch "Fetching values from the database" New topic
Author

Fetching values from the database

Chandra Swaminathan
Greenhorn

Joined: Nov 30, 2011
Posts: 6
I have a mysql table named 'customer'. serialnumber (int), name(varchar), gender(varchar) are the table fields.

I have a int variable a = 2.

I want to fetch the value from the table when serialnumber = a. That is when the serialnumber = 2 it should display the particular customer's name.



This throws me nothing. But when i give the number instead a in rs.execute Query it displays the customer name. How to solve this and what is my mistake??
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18986
    
    8

Did you assume that the JDBC driver would somehow interpret the second "a" in that character string as the name of a Java variable? If so, that was your mistake.

What should you do? I would use a prepared statement like this:
Chandra Swaminathan
Greenhorn

Joined: Nov 30, 2011
Posts: 6
I did made a mistake.
I treated a like a literal, instead of a variable. Then updated the query like this:



It did worked!

Thank you!
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3611
    
  60

Two problems with that:

1) serialnumber is a number. The like operator compares strings. You actually want to test equality here: where serialnumber = 2

2) As already hinted by Paul, use PreparedStatement and bind variables. They are inherently safer (protect you from sql injection attacks), usually more performant and definitely easier to use (no need to quote and escape strings). I'm not going to explain it further here, as all good JDBC tutorials cover this (if you read a JDBC tutorial that does not cover PreparedStatement and bind variables, stop reading it). Tutorials on Oracle's web are probably among the best.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Fetching values from the database