0

I'm creating a MySQL table in Java. I don't want to have one big string since I think it looks messy.

Is there something like this when creating a table?

            try (final PreparedStatement statement = this.connection.prepareStatement("CREATE TABLE IF NOT EXISTS " + this.table + "(?, ?)")) {
            statement.setString(1, "id TINYINT PRIMARY KEY NOT NULL");
            statement.setString(2, "another_column TINYTEXT NOT NULL");

            statement.execute();

Regards

dennisp
  • 93
  • 1
  • 7
  • Well, It will not work since you set twice the same parameter. And this would not work since the parameter you provide would be put between quotes (I don't even think the JDBC allows DDL query in a `PreparedStatement`). You need to generate your query yourself. – AxelH Apr 18 '19 at 12:18
  • 1
    Parameters are for values only, not for fragments of SQL. – Mark Rotteveel Apr 18 '19 at 16:46

1 Answers1

1

You can't create the table like this.
Use prepared statements to pass values to placeholders and not table names or column names.
Change to this:

PreparedStatement statement = this.connection.prepareStatement(
    "CREATE TABLE IF NOT EXISTS " + this.table + " (" + 
    "id TINYINT PRIMARY KEY NOT NULL, another_column TINYTEXT NOT NULL)"
);
statement.execute();
forpas
  • 160,666
  • 10
  • 38
  • 76