创建表会引发SQL异常

时间:2017-09-18 15:19:51

标签: java sql database javadb

我想用一个表创建一个简单的SQL数据库。第8行抛出SQLSyntaxErrorException。

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 个答案:

答案 0 :(得分: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后面有另一个列名。由于没有导致错误。

答案 1 :(得分:0)

您的sql语句不正确:

  • 最后还有额外的,

这应该有效:

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