gpt4 book ai didi

java - SQL select 语句无法正确打印

转载 作者:行者123 更新时间:2023-11-29 18:11:57 24 4
gpt4 key购买 nike

我有一个 MYSQL 数据库,其中的 select 语句类无法正常工作。它没有给我错误,但除了顶部标签之外不打印任何内容。这是我的选择语句代码

public String selectStatement() {
try {

PreparedStatement select = con.prepareStatement("SELECT ? FROM nickdimfans WHERE FirstName = ?");

select.setString(1, "*");
select.setString(2, "'Nick'");

ResultSet rs = select.executeQuery();

StringBuilder selectStatement = new StringBuilder();
selectStatement.append("ID\tFirst Name\tLast Name\tEmail\n");
while (rs.next()) {
selectStatement.append(rs.getInt("ID"));
selectStatement.append("\t");
selectStatement.append(rs.getString("FirstName"));
selectStatement.append("\t");
selectStatement.append(rs.getString("LastName"));
selectStatement.append("\t");
selectStatement.append(rs.getString("Email"));
selectStatement.append("\n");
}
System.out.println(selectStatement);

return selectStatement.toString();

} catch (SQLException e) {
e.printStackTrace();
}
return "error check selectStatement";
}

最佳答案

在打印标题之前,您可能需要检查 RS 是否为空。'

ResultSet rs = statement.execute();
if (rs.next()){

StringBuilder selectStatement = new StringBuilder();
selectStatement.append("ID\tFirst Name\tLast Name\tEmail\n");
while (rs.next()) {
selectStatement.append(rs.getInt("ID"));
selectStatement.append("\t");
selectStatement.append(rs.getString("FirstName"));
selectStatement.append("\t");
selectStatement.append(rs.getString("LastName"));
selectStatement.append("\t");
selectStatement.append(rs.getString("Email"));
selectStatement.append("\n");
}
System.out.println(selectStatement);
}

关于java - SQL select 语句无法正确打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47314630/

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