0

我在尝试使用 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) 方法,以便它可以查找与播放器关联的所有信息并写回套接字。我在这里做错了什么?

4

1 回答 1

1

我认为您的查询不正确。尝试这样的事情

String hql = "SELECT * FROM Player P WHERE P.playerName = :playerName";         
Query query = session.createQuery(hql); 
query.setParameter("playerName", usr);
于 2013-07-28T13:23:24.913 回答