SQL和问号的问题

时间:2011-06-13 06:49:51

标签: java sql

我正在尝试使用PreparedStatemnent执行脚本:

import java.sql.*;

public class DeclaredStatement {

  public static void main(String[] args) throws SQLException {

    try {      
      Class.forName("com.mysql.jdbc.Driver");
      Connection conn = 
        DriverManager.getConnection("jdbc:mysql://localhost/test");
      PreparedStatement stmt = conn.prepareStatement(""
        + "SELECT TITLE FROM MOVIES"
        + "WHERE year_made >= ? "
        + "and year_made < ?");

      for (int decadeStart=1920;decadeStart<2000;decadeStart+=10) {
         System.out.println("==== Movies of the " + decadeStart + "s ====");
         stmt.setInt(1, decadeStart);
         stmt.setInt(2, decadeStart+10);
         ResultSet rs = stmt.executeQuery();
         while (rs.next()) {
           System.out.println(rs.getString(1)+" - "+rs.getInt(2));
         }
      }

    } catch (SQLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }

  }

}

错误是:

run:
==== Movies of the 1920s ====
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '>= 1920 and year_made < 1930' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.Util.getInstance(Util.java:384)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
    at client.DeclaredStatement.main(DeclaredStatement.java:26)
BUILD SUCCESSFUL (total time: 0 seconds)

2 个答案:

答案 0 :(得分:7)

在您构建查询时,MOVIESWHERE之间的空格似乎不一样,这将导致SELECT TITLE FROM MOVIESWHERE year_made...

答案 1 :(得分:2)

后你缺少空间
SELECT TITLE FROM MOVIES

之前WHERE