简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM