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 workbench 6.0中有效但在我的Java App中无法通过JDBC工作,我是SQl和JDBC的新手,我意识到我的结果集可能不是100%这个查询也可能是问题,它来自一个共享方法,在这种情况下我更关心SQL查询语句。
答案 0 :(得分:2)
问题是您在最后选择的列名与FROM
之间缺少空格。要解释您的查询,您有:
String query = "SELECT ..., CarLot.OWNER.Last_Name"+ // oops, no space!
"FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
这个错误很常见,因为在一行的末尾很难看到丢失的空格,但是有一种代码风格用于解决这个问题 - 我在 start 中添加了空格该行,如下:
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";
每一行都以quote-space开头,即" ...
,所以现在当一个换行的字符串缺少一个空格时非常明显,而且因为SQL(通常)空白不敏感,你可以在最终也没有造成任何问题。
答案 1 :(得分: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 injection攻击
答案 2 :(得分:1)
查询的第一行和第二行之间没有空格,因此您有select
... CarLot.OWNER.Last_NameFROM CarLot
....添加空间,看看会发生什么。