kappaprajd
kappaprajd

Reputation: 83

MySQL syntax error while working with placeholders in Python

I want to create table name with a one column but I'm getting this error:

mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''test' 'int')' at line 1

The code I'm trying to use:

table_name = 'test'
create_table = f'CREATE TABLE {table_name} (%s %s)'
cursor.execute(create_table,(headers[0], data_types[0],))

I've tried typing manually table name, column name and data type but it ended up with the same result. I've seen a lot of solutions on this problem but none of them worked out with this case

Upvotes: 0

Views: 201

Answers (1)

GMB
GMB

Reputation: 222612

You just can't bind this part of the query. Bind parameters are essentially used to replace litterals in the query, not random part of it. Under the hood, your RDBMS must be able to prepare the query without seeing the values of the bind parameters.

In this case, you need string concatenation:

table_name = 'test'
create_table = f'CREATE TABLE {table_name} ({headers[0]} {data_types[0]})';
cursor.execute(create_table);

Upvotes: 1

Related Questions