-1

I am trying to create a new table through a MySQL command in C#. The problem is that even though without the parameter all works fine(aka having a fixed name) when I add the parameter it doesn't run. Error: '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 '@tableName ( studentid INT NOT' at line 1' Here is my code

            MySqlCommand create = new MySqlCommand(@"CREATE TABLE iadatabase.@tableName (
                                                studentid INT NOT NULL AUTO_INCREMENT,
                                                studentname varchar(30) NOT NULL,
                                                absenses INT NULL,
                                                CONSTRAINT table_pk PRIMARY KEY (studentid)
                                                )
                                                ENGINE=InnoDB
                                                DEFAULT CHARSET=utf8
                                                COLLATE=utf8_general_ci
                                                AUTO_INCREMENT=1;
                                                ;", connection);
        create.Parameters.AddWithValue("@tableName", tableName);
        create.ExecuteNonQuery();
        create.Parameters.Clear();
jakev
  • 91
  • 6
  • 4
    You cannot parametrize table name. You need to concatenate/interpolate DDL string. Be aware that could lead to SQL injection. – Lukasz Szozda Sep 08 '18 at 16:03

1 Answers1

0

The name of the table you are selecting from cannot be generated from a parameter. If you need to do this you will need to do a string replacement on the SQL itself.

PhillipH
  • 5,938
  • 1
  • 13
  • 24