2

I am trying to make a variable Table name through Java.

My code is :

public void createTable(String tableName){

    try {
        Statement stmt = con.createStatement();
        stmt.executeUpdate("CREATE TABLE '"+tableName+"'" +
                   "(id INTEGER not NULL, " +
                   " username VARCHAR(255), " + 
                   " pass VARCHAR(255), " + 
                   " age INTEGER, " + 
                   " PRIMARY KEY ( id ))");

    }
    catch (SQLException e){
        e.printStackTrace();

    }


}

It gives me a syntax error saying:

Incorrect syntax near 'VariableTableNameIChose'.

Does anyone have any ideas?

1
  • tableName+"'" - Space is missing here. Commented Dec 7, 2014 at 13:27

2 Answers 2

2

It could be one of 2 things or the combination of both.

Maybe the single quotes around the table name are not valid in your database. So do like this:

    stmt.executeUpdate("CREATE TABLE "+tableName+" " +
               "(id INTEGER not NULL, " +
               " username VARCHAR(255), " + 
               " pass VARCHAR(255), " + 
               " age INTEGER, " + 
               " PRIMARY KEY ( id ))");

Or maybe you need a spaces between the table name and the ( following after:

    Statement stmt = con.createStatement();
    //                                              v this one was missing
    stmt.executeUpdate("CREATE TABLE '"+tableName+"' " +
               "(id INTEGER not NULL, " +
               " username VARCHAR(255), " + 
               " pass VARCHAR(255), " + 
               " age INTEGER, " + 
               " PRIMARY KEY ( id ))");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! This worked! (The first solution)
1

The table name is an identifier. Identifiers do not use single quotes (in standard SQL).

"CREATE TABLE '"+tableName+"' "

Will result in

CREATE TABLE 'foobar'

which is invalid SQL. You need to remove the single quotes:

"CREATE TABLE "+tableName+" " + ...

As the table name is apparently a user input, you might actually want to use quoted identifiers (although this is in general a bad idea). Identifiers are quoted using double quotes in the SQL standard:

"CREATE TABLE \""+tableName+"\" " + ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.