gpt4 book ai didi

Java 在单独的行上打印数据库记录

转载 作者:太空宇宙 更新时间:2023-11-03 11:30:44 25 4
gpt4 key购买 nike

我有一个 JDBC 程序,它从 MySQL 数据库中获取记录并打印出结果。用户可以通过选择不同的复选框以仅显示某些结果来从数据库中选择他们想要的结果。

下面是获取记录并打印出来的方法:

private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
result += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
result += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
result += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
result += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
result += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
result += zip + " ";
}
// print the results
}
System.out.println(result);
results.setText(result);

stmt.close();
}

目前,如果我选择前三个复选框,我会得到输出:

1 Smith, Tim 12 Elm St 2 Jones, Tom 435 Oak Dr 3 Avery, Bill 623 Ash Ave 4 Kerr, Debra 1573 Yew Crt 

然而,我追求的输出是:

1, Smith, Tim, 12 Elm St
2, Jones, Tom, 435 Oak Dr
3, Avery, Bill, 623 Ash Ave
4, Kerr, Debra, 1573 Yew Crt

有什么方法可以在数据库中的每条记录之后添加一个新行,以及每条记录中的项目之间的逗号?我不熟悉 JDBC 和 MySQL 连接,因此非常感谢任何帮助或提示。

最佳答案

您可以在 while 循环结束前打印每一个结果,然后它会在新行中打印每条记录。

private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
String singleResult = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
singleResult += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
singleResult += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
singleResult += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
singleResult += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
singleResult += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
singleResult += zip + " ";
}
System.out.println(singleResult);
result +=singleResult;
}
//System.out.println(result);
results.setText(result);

stmt.close();
}

或者您可以在关闭 while 循环之前附加行分隔符

System.out.println(singleResult);
result +=singleResult;
result +="\n";

关于Java 在单独的行上打印数据库记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50083076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com