aspose file tools*
The moose likes JDBC 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
Bookmark "search in database" Watch "search in database" New topic
Author

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();

try{
st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
if(rs.getString("userName").equals(userName)){
info.setHost(rs.getString("hostName"));
list.add(info.getHost());
}

}

}
catch(SQLException e){
e.printStackTrace();
logger.info("couldn't find the host name");
e.printStackTrace();
}
return list;
}
Error:

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
Author
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: http://aspose.com/file-tools
 
subject: search in database