简体   繁体   English

在 Python 中使用占位符时出现 MySQL 语法错误

[英]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; mysql.connector.errors.ProgrammingError: 1064 (42000): 你的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' 'int')' at line 1检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的 ''test' 'int')' 附近使用的正确语法

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.在幕后,您的 RDBMS 必须能够在不查看绑定参数值的情况下准备查询。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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