2012-02-12 82 views
1

我用Java创建了一个数据库的连接,我想显示两个表中的数据。在java中显示两个表的值

在查询语句中,我使用了JOIN命令,但是我正在努力解决语法错误。 希望得到一些建议。

try 
    { 
     Class.forName(driverName); 
     connection = DriverManager.getConnection(SourceURL, user, password); 


     Statement listDisplay = connection.createStatement(); 
     ResultSet displayAll = listDisplay.executeQuery("SELECT AnimalType.typeID, AnimalType.description, Animal.name " 
                +"FROM Animal " 
                +"JOIN AnimalType "  
                +"ON AnimalType.typeID = Animal.typeIDForeign"); 
     while(displayAll.next()) 
     { 
      int typeId = displayAll.getInt(1); 
      String description = displayAll.getString(2); 
      String name = displayAll.getString(3); 

      System.out.println(typeId + " " + description + " " + name); 
     } 

     connection.close(); 

     } 
     catch(SQLException sql) 
     { 
      JOptionPane.showMessageDialog(null, sql.toString()); 
     } 
     catch(ClassNotFoundException exe) 
     { 
      JOptionPane.showMessageDialog(null, exe.toString()); 
     } 

它会工作,我想在这里做什么?

问候 阿里安

+2

请张贴堆栈跟踪。 – Paul 2012-02-12 14:53:58

+0

由于您可以在命令行应用程序中重现相同的错误。没有GUI,这与Swing没有任何关系。 – 2012-02-12 15:02:57

+0

是的。谢谢。对查询做了轻微的修改,现在很好......谢谢。 (“SELECT AnimalType.typeID,AnimalType.description,Animal.name”+“FROM AnimalType,Animal”+“WHERE AnimalType.typeID = Animal.typeIDForeign”); – Arianule 2012-02-12 15:10:42

回答

1

我通常做它有点像这样:

if (displayAll.first()) 
{ 
    do 
    { 
     int typeId = displayAll.getInt(1); 
     String description = displayAll.getString(2); 
     String name = displayAll.getString(3); 

     System.out.println(typeId + " " + description + " " + name); 
    } while(displayAll.next()); 
} 
displayAll.close(); 
listDisplay.close();