1
Statement stmt = null;

    String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name"+
            "FROM CarLot.CAR, CarLot.OWNER" +
                    " WHERE CarLot.CAR.Sold_Status = TRUE";

    try {
        con = getConnection();
        stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery(query);

         String heading1 = "    Make"; String heading2 = "    Model"; String
         heading3 = "    Year"; String heading4="Sold Status";
         System.out.printf("%-20s %-20s %-20s %-20s\n", heading1, heading2,
         heading3,heading4);
         System.out.println("--------------------------------------------------------------------------\n");

        while (rs.next()) {

            String make = rs.getString("car.Make");
            String model = rs.getString("car.Model");
            int carYear = rs.getInt("car.Year");
            boolean soldStatus = rs.getBoolean("car.Sold_Status");
            String firstName = rs.getString("owner.First_Name");

            System.out.printf("%-2s %-20s %-20s %-20s %-20s\n", 
              make, model, carYear,soldStatus,firstName);

             }
        System.out.println("\n\n");
    } finally {
        stmt.close();

    }

我遇到的问题是 SQL 语法错误,该语法在 MySql 工作台 6.0 中有效,但不能通过 JDBC 在我的 Java 应用程序中工作,我是 SQl 和 JDBC 的新手,我意识到我的结果集可能不是 100% 这个查询和这也可能是问题所在,它来自共享方法,在这种情况下,我更关心 SQL 查询语句。

4

3 回答 3

2

问题是您在最后选择的列名和FROM. 为了解释您的查询,您有:

String query = "SELECT ..., CarLot.OWNER.Last_Name"+ // oops, no space!
        "FROM CarLot.CAR, CarLot.OWNER" +
         " WHERE CarLot.CAR.Sold_Status = TRUE";

这个错误很常见,因为在行尾很难看到缺少空格,但是我使用了一种代码样式来解决这个问题 - 我在行首放置空格如下所示:

String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name"+
    " FROM CarLot.CAR, CarLot.OWNER" +
    " WHERE CarLot.CAR.Sold_Status = TRUE";

每行都以引号空格开头,即" ...,所以现在当断行字符串缺少空格时非常明显,而且由于 SQL(通常)对空格不敏感,您也可以在末尾放置空格而不会造成任何问题。

于 2013-11-15T00:28:25.467 回答
2

FROM在子句前加一个空格

String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name" +
           " FROM CarLot.CAR, CarLot.OWNER" +
                    " WHERE CarLot.CAR.Sold_Status = TRUE";

旁白:考虑使用PreparedStatement以防止SQL 注入攻击

于 2013-11-15T00:28:35.750 回答
1

查询的第一行和第二行之间没有空格,因此您有select... CarLot.OWNER.Last_NameFROM CarLot... 。添加空间,看看会发生什么。

于 2013-11-15T00:29:07.003 回答