Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

search in database

 
zohreh talebi
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 531
Java Mac OS X Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic