SQL select语句打印不正确

时间:2017-11-15 18:21:32

标签: java mysql sql

我有一个带有select语句类的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";
}

1 个答案:

答案 0 :(得分:0)

您可能想要在打印标题之前检查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);
}