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 search in 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 "search in database" Watch "search in database" New topic

search in database

zohreh talebi
Ranch Hand

Joined: Sep 01, 2006
Posts: 41
Dear friends,

I want to search a value as hostName but it has an error from syntax.
Please help me.
This is my search method and error:

public List searchHost(String userName){

String sql = "SELECT * FROM netmessenger WHERE userName = "+ userName + "''";
Statement st;
List list = new ArrayList();

st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);


catch(SQLException e){
e.printStackTrace();"couldn't find the host name");
return list;

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
Maryam Nouhnejad
Ranch Hand

Joined: Oct 04, 2006
Posts: 39
my dear friend you have to write it like this :
String sql = "SELECT * FROM netmessenger WHERE userName = '"+ userName + "'";

But I'm not sure why you have used 'WHERE' in your syntax and again checked the user names by your ResultSet object?...
Masoud Kalali
Ranch Hand

Joined: Jul 08, 2004
Posts: 531

first you will need to use "'"+username+"'" to make it works as it is going to be an string and mysql needs strings to be single quted.
secondly you do not need to check username when you are iterating resultset because you perform that check in your sql statement so a part of your code
mqy looks like this

Masoud Kalali
Software Engineer - My Weblog - GlassFish Security
I agree. Here's the link:
subject: search in database
It's not a secret anymore!