2011-06-13 100 views
0

我試圖用PreparedStatemnent執行腳本:問題的SQL和問號

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) 
+0

年份列的類型是什麼? – pap 2011-06-13 06:52:54

+0

此外,System.out.println(rs.getString(1)+「 - 」+ rs.getInt(2))應該失敗,因爲您只從表中選擇一列。 – pap 2011-06-13 06:53:27

回答

7

當您建立查詢時,看起來不像您在MOVIESWHERE之間有一個空格,這將導致SELECT TITLE FROM MOVIESWHERE year_made...

+0

這總是我在調試過程中遇到SQL錯誤以獲取實際語句字符串並嘗試在查詢工具中執行它的第一步... – 2011-06-13 06:57:47

+0

是的,它總是我的第一步。在這種情況下,我可能不會將語句字符串拆分成3行,然後在發生問題之前可能會發現問題! – 2011-06-13 07:00:29

+0

謝謝大家 – 2011-06-13 07:02:15

2

你缺少空間後

SELECT TITLE FROM MOVIES 

之前WHERE