2015-05-28 116 views
1

我有一个查询在SQLyog中运行良好,但不在eclipse中。我调试时显示的错误是“找不到列”。sql查询在eclipse中不起作用

这里是我的查询:

String searchQuery = "select AVG(Rating) from rating where CoursesID=? and MONTH(dtDate)=? group by dtDate"; 

表:

ID  | CoursesID | Rating | Comment | dtDate 

11111 | SKM3207 | 5  | No  | 2015-05-20 

的Java

//preparing some objects for connection 
     Connection currentCon = null; 
     ResultSet rs = null; 
     PreparedStatement pstmt = null; 
     //double totalRate = 0.0; 

     Vector<String> monthRating = new Vector<String>(); 

     try{ 
      String searchQuery = "select AVG(Rating) from rating where CoursesID=? and MONTH(dtDate)=? group by dtDate"; 

      //connect to DB 
      currentCon = ConnectionManager.getConnection(); 
      pstmt=currentCon.prepareStatement(searchQuery); 
      pstmt.setString(1, CoursesID); 
      pstmt.setString(2, fmonth); 
      rs = pstmt.executeQuery(); 

      while(rs.next()){ 
       monthRating.add(rs.getString("Rating")); 
       //String avg = rs.getString(1); 
       //totalRate = Double.parseDouble(avg); 
      } 
     } 

     catch (Exception ex){ 
      System.out.println("Log In failed: An Exception has occurred! " + ex); 
     } 

     //some exception handling 
     finally{ 
      if (rs != null) { 
       try { 
       rs.close(); 
       } catch (Exception e) {} 
       rs = null; 
       } 

      if (pstmt != null) { 
       try { 
       pstmt.close(); 
       } catch (Exception e) {} 
       pstmt = null; 
       } 

      if (currentCon != null) { 
       try { 
       currentCon.close(); 
       } catch (Exception e) { 
       } 

       currentCon = null; 
      } 
     } 

      return monthRating; 

是,任何需要添加到其中,因此它可以在Eclipse中运行?

+0

请出示你的表 –

+0

什么你连接字符串到数据库看起来像? –

+0

检查你的表'create'语句 – Kushal

回答

1

您正在使用评级为rs.getString("Rating")而评级在SQL语句中没有别名,而在聚集中使用。只需添加一个别名

SELECT AVG(Rating) AS Rating .... 
+0

谢谢!!!!!!有用!!!! :D – Sue

1

在您的查询,你不为你检索列定义一个名字:

select AVG(Rating) from ... 

所以,当你执行这个:

rs.getString("Rating") 

你得到一个异常。查询更改为:

select AVG(Rating) AS Rating from ... 
+0

谢谢!!!!!!有用!!!! :D – Sue

1
monthRating.add(rs.getString("Rating")); 

您取出由resultSetRating列,但查询AVG(Rating)为列名,以便将其更改为,

monthRating.add(rs.getString("AVG(Rating)"); 
+1

谢谢!!!!!!有用!!!! :d – Sue