0
    String sql2 = "create table ? ( id int not null auto_increment, fullname
    varchar(30) not null, primary key (id) )";

    PreparedStatement stmt2 = conn.prepareStatement(sql2);

    stmt2.setString(1, username);

    stmt2.execute();

    stmt2.close();

from above statements, i got error message('john' as table name):

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 ''john' ( id int not null 
auto_increment, fullname varchar(30) not null, primary ' at line 1

eclipse says the error is in this line:

stmt2.execute();

please help guys...tq

Shahril
  • 105
  • 1
  • 1
  • 9

1 Answers1

1

You can't use a parameter for the table name in a CREATE TABLE statement.

Instead simply build the SQL string using the variable:

String sql2 = "create table " + username + " ( id int not null auto_increment, fullname
varchar(30) not null, primary key (id) )";

Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(sql2); 
wero
  • 32,544
  • 3
  • 59
  • 84
  • but most people say such way can lead to sql injection and better to be avoided..? – Shahril Jun 17 '16 at 16:04
  • 1
    @Shahril yes, if you run this statement without sanitizing the input you are in trouble. But nevertheless you can only use parameters to pass values but not names of tables, columns etc. – wero Jun 17 '16 at 16:09
  • thanks so much...:) i'm a newbie, so i don't really understand when u said 'sanitizing the input'. really appreciate if u can elaborate or at least point me to the right direction.. thanks again..:) – Shahril Jun 17 '16 at 16:20
  • @Shahril you should test that `username` is a valid table identifier. A first step could be to only allow characters [a-zA-Z]... – wero Jun 17 '16 at 16:24