2017-09-18 112 views
-2

我想用一個表創建一個簡單的SQL數據庫。第8行拋出一個SQLSyntaxErrorException。創建表拋出SQL異常

public class LoadDatabase { 
public static void main(String[] args) { 

    //if createConnection() returns a connection issue SQL Statements 
    try (Connection connection = ConnectToDatabase.createConnection()){ 
     Statement command = connection.createStatement(); 
     //gives SQL command "create table" to database 
     command.executeUpdate(ConnectToDatabase.CREATE_TABLE); 
     command.close(); 
    } catch (ClassNotFoundException e) { 
     System.err.println("Could not find database driver"); 
    } catch (SQLException e) { 
     System.err.println("SQL Error"); 
     e.printStackTrace(); 
    } 

} 
} 

這是表

//SQL command to create a new table as constant variable 
public final static String CREATE_TABLE = 
     "CREATE TABLE BOOK_INVENTORY (" + 
     "TITLE VARCHAR, " + 
     "AUTHOR VARCHAR, " + 
     "PAGES INT, " + 
     "ISBN VARCHAR, " + 
    ")"; 
+2

不確定在列表列表中是否允許拖尾','。 – luk2302

+0

您的'ISBN'列後面有一個尾部','。 – Siyual

+0

@ luk2302這是不允許的 –

回答

0

你的SQL語句是不正確:

  • 有額外到底,

這應該工作:

CREATE TABLE BOOK_INVENTORY (" + 
     "TITLE VARCHAR, " + 
     "AUTHOR VARCHAR, " + 
     "PAGES INT, " + 
     "ISBN VARCHAR" + 
    ") 
+0

雖然建議'VARCHAR'的大小,它們不是強制性的,並不是這種例外的原因。但是,這仍然是很好的建議。 – JJT

+1

@JJT - 你是對的,謝謝 –

1

唯一的例外是在SQL語句中的最後一個逗號引起的。

//SQL command to create a new table as constant variable 
public final static String CREATE_TABLE = 
    "CREATE TABLE BOOK_INVENTORY (" + 
    "TITLE VARCHAR, " + 
    "AUTHOR VARCHAR, " + 
    "PAGES INT, " + 
    "ISBN VARCHAR, " + 
")"; 

更改爲:

//SQL command to create a new table as constant variable 
public final static String CREATE_TABLE = 
    "CREATE TABLE BOOK_INVENTORY (" + 
    "TITLE VARCHAR, " + 
    "AUTHOR VARCHAR, " + 
    "PAGES INT, " + 
    "ISBN VARCHAR" + 
")"; 

的逗號是暗示有ISBN陸續列名。由於沒有導致錯誤。