开发者

Problem with SQL and question mark

I'm trying to execute the script with 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();
    }

  }

}

The error is:

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)


It doesn't look like you've got a space between MOVIES and WHERE when you build up your query, which will result in SELECT TITLE FROM MOVIESWHERE year_made....


You are missing space after

SELECT TITLE FROM MOVIES

before WHERE

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜