File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases 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
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Fetching values from the database" Watch "Fetching values from the database" New topic

Fetching values from the database

Chandra Swaminathan

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

Joined: Oct 14, 2005
Posts: 19973

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

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

Joined: Aug 22, 2010
Posts: 3733

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:
subject: Fetching values from the database
jQuery in Action, 3rd edition