Reputation: 159
I am having problem trying to execute a SQL/HQL statement using the WHERE clause.
The application connects and executes this method when called without errors:
public void listPlayers( ){
Session session = sessionFactory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List players = session.createQuery("FROM Player").list();
for (Iterator iterator =
players.iterator(); iterator.hasNext();){
Player player = (Player) iterator.next();
String tmpMessage = player.getFirstName().toString();
System.out.println(tmpMessage);
writer.write("First Name: "+player.getPlayerName()+", Wealth: "+player.getWealth()+"\r\n");
writer.flush();
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
BUT, when I try to do this; I get an error: player_name field not found:
public void loadPlayer(String usr){
Session session = sessionFactory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
String hql = "SELECT * FROM Player P WHERE P.player_name = "+usr;
Query query = session.createQuery(hql);
List players = query.list();
for (Iterator iterator =
players.iterator(); iterator.hasNext();){
Player player = (Player) iterator.next();
System.out.print(" Location: " + player.getLocation());
System.out.println(" Wealth: " + player.getWealth());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
My mySQL database has a Table named Player, with pID, player_name, location, wealth as column values
I am attempting to pass playername to the loadPlayer(String username) method so it can look up all information associated with the player and write back to socket. What am I doing wrong here?
Upvotes: 0
Views: 135
Reputation: 638
i think your query is not correct. try something like this
String hql = "SELECT * FROM Player P WHERE P.playerName = :playerName";
Query query = session.createQuery(hql);
query.setParameter("playerName", usr);
Upvotes: 1