我在尝试使用WHERE子句执行SQL / HQL语句时遇到问题。
应用程序在没有错误的情况下连接并执行此方法:
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();
}
}
但是,当我尝试这样做时;我收到一个错误:找不到player_name字段:
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();
}
}
我的mySQL数据库有一个名为Player的表,其中包含pID,player_name,location,财富作为列值
我正在尝试将playername传递给loadPlayer(String username)方法,以便它可以查找与播放器关联的所有信息并写回套接字。我在这里做错了什么?
答案 0 :(得分:1)
我认为您的查询不正确。 试试这样的事情
String hql = "SELECT * FROM Player P WHERE P.playerName = :playerName";
Query query = session.createQuery(hql);
query.setParameter("playerName", usr);