如何从MySQL中检索所有名称?

时间:2016-04-29 13:37:41

标签: java mysql jdbc

我想从MySQL检索所有名称和行数到java。到目前为止,我只能检索总行数,但我只得到姓氏。这里有什么问题?

StaffManagement.java

adminAPI api= new adminAPI();
try {
      int num= api.displayCheckBoxAndLabel();
      String allName= api.displayName();
      System.out.println(num+allName);
}

adminAPI

public int displayCheckBoxAndLabel() throws Exception // get the number of row 
    {
        int count = 0;
        String sql="Select count(*) AS adminID from admin";
        DatabaseConnection db = new DatabaseConnection();
        Connection  conn =db.getConnection();
        PreparedStatement  ps = conn.prepareStatement(sql);
         ResultSet rs = ps.executeQuery();
         while(rs.next()) 
         {  
             count= rs.getInt("adminID");

         }
         ps.close();
         rs.close();
         conn.close();
         return count ;
    }

    public String displayName() throws Exception // get all the name 
    {
        String name = null;
        String sql="Select name from admin";
        DatabaseConnection db = new DatabaseConnection();
        Connection  conn =db.getConnection();
        PreparedStatement  ps = conn.prepareStatement(sql);
         ResultSet rs = ps.executeQuery();
         while(rs.next()) 
         {  
             name= rs.getString("name");

         }
         ps.close();
         rs.close();
         conn.close();
         return name ;
    }

2 个答案:

答案 0 :(得分:1)

您目前返回一个String,并且您的方法会迭代所有管理员名称(但会在最后一行之后终止,以便您的结果)。相反,构建一个List名称并返回该名称。您还可以使用try-with-resources close close ConnectionStatementResultSet个实例。像

这样的东西
public List<String> displayName() throws Exception // get all the name
{
    String sql = "Select name from admin";
    List<String> names = new ArrayList<>();
    DatabaseConnection db = new DatabaseConnection();
    try (Connection conn = db.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            names.add(rs.getString("name"));
        }
    }
    return names;
}

答案 1 :(得分:1)

这可能会有所帮助

private String names[];
int i = 0;

while (rs.next()) {
names[i] = rs.getString("name");
i++;
}

然后,您可以使用for循环返回StaffManagement.java中的每个名称