如何使用jdbc获取一列中的所有行

时间:2016-04-23 22:07:07

标签: java mysql jdbc

我的团队表ID和团队名称

中有2列

这是我的方法

public List<String> getallteams() {
    Connection conn = null;
    ArrayList users = new ArrayList();
    List<String> teams = new ArrayList();
    try {
        conn = DBConnection.openConnection();

        String sql = " SELECT * FROM teams  ";


        PreparedStatement stmt = conn.prepareStatement(sql);

        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {

            String t1 = rs.getString(1);
            String t2 = rs.getString(2);
            String t3 = rs.getString(3);
            String t4 = rs.getString(4);
            String t5 = rs.getString(5);
            String t6 = rs.getString(6);


            String[] finalresult1 = {t1,t2,t3,t4,t5,t6 };



            teams = Arrays.asList(finalresult1);


                System.out.println(teams.get(1));
        }

    } catch (SQLException ex) {
        Logger.getLogger(UsersDaoImp.class.getName()).log(Level.SEVERE, null, ex);

    } finally {

        DBConnection.closeConnection(conn);
    }

    return teams;

}

我是mysqli的新手,所以在这里苦苦挣扎

但是它给了我java.sql.SQLException:列索引超出范围,2&gt; 1错误

1 个答案:

答案 0 :(得分:1)

你刚才说'#34;我有2栏&#34; (id和name),所以不要尝试检索第3,4,5和6列。

while (rs.next()) {
    String id   = rs.getString(1);
    String name = rs.getString(2);
    System.out.println("id=" + id + ", name=" + name);
}

如果第二列名为teamname,并且您想要所有团队名称的列表,请执行以下操作:

List<String> teams = new ArrayList<>();
try (Connection conn = DBConnection.openConnection()) {
    String sql = "SELECT teamname FROM teams";
    try (PreparedStatement stmt = conn.prepareStatement(sql);
         ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            teams.add(rs.getString("teamname"));
        }
    }
}

System.out.println("First team: " + teams.get(1));