我有一个包含列的数据库表:名称,住所,联系人。而且我只想检索'联系人列中的值'成阵列。以下代码是我写的:
List l = new ArrayList();
try {
String sql = "select * from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String con = rs.getString("Contact");
l.add(con);
System.out.println(l);
}
} catch (Exception e) {
e.getMessage();
}
但这会产生以下结果:
[0547615632]
[0547615632, 0246687643]
[0547615632, 0246687643, 0558581764]
虽然表格中只有3条记录,每条记录都有联系价值
请问如何编写代码,以便我只能获得一个显示结果的数组,如下所示:
[0547615632, 0246687643, 0558581764]
非常感谢你。
答案 0 :(得分:2)
您应该将打印命令移出while循环:
List l = new ArrayList();
try {
String sql = "select * from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String con = rs.getString("Contact");
l.add(con);
}
} catch (Exception e) {
e.getMessage();
}
System.out.println(l);
OR 仅在每次迭代中打印当前元素;
List l = new ArrayList();
try {
String sql = "select * from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String con = rs.getString("Contact");
l.add(con);
System.out.print(con + " ");
}
} catch (Exception e) {
e.getMessage();
}