Creating a table throws SQL Exception

436 views Asked by At

I would like to create a simple SQL database with one table. Line 8 throws a 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();
    }

}
}

This is the table

//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

There are 2 answers

2
AudioBubble On

Your sql statement is incorrect:

  • There was extra , in the end.

This should work:

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

The exception is caused by the final comma in your SQL statement.

//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, " +
")";

Change to:

//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" +
")";

The comma is implying that there is another column name after ISBN. Since there isn't it is causing the error.