我在尝试使用 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 的 Table,以 pID、player_name、location、weak 为列值
我正在尝试将 playername 传递给 loadPlayer(String username) 方法,以便它可以查找与播放器关联的所有信息并写回套接字。我在这里做错了什么?