This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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: 18541
    
    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: 3606
    
  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.
 
 
subject: Fetching values from the database
 
Similar Threads
problem in inserting session data in jsp/servlet application
Online Shopping
how to upload pdf files to My sql with java
Access Dbase with Http connection
Exception! Column not found!?