我想动态更改我插入数据的表的变量名。
目前这个可以工作。
但是,当我尝试对这个表名(在这种情况下为“FoodPorn”)进行相同的操作时,但对于像这个示例中的动态表名(MachinePorn)这样的表名,情况就不同了。
我收到了这个错误。
这让我相信我不能这样做,因此我想问如何做到最终可以传入表的变量名,而不是每次都硬编码。
目前这个可以工作。
def dataEntry(subreddit, _title, _post_url, _imageURL):
cnx = mysql.connector.connect(**config)
c = cnx.cursor()
insert = ("""INSERT INTO FoodPorn
(subreddit, title, post_url, imageURL)
VALUES (%s, %s, %s, %s)""")
data_value = (subreddit, _title, _post_url, _imageURL)
c.execute(insert, data_value)
cnx.commit()
c.close()
cnx.close()
dataEntry("fake", "fake", "fake", "fake")
但是,当我尝试对这个表名(在这种情况下为“FoodPorn”)进行相同的操作时,但对于像这个示例中的动态表名(MachinePorn)这样的表名,情况就不同了。
def dataEntry(subreddit, _title, _post_url, _imageURL):
cnx = mysql.connector.connect(**config)
c = cnx.cursor()
insert = ("""INSERT INTO subredditName
(subreddit, title, post_url, imageURL)
VALUES (%s, %s, %s, %s, %s)""")
data_value = ("MachinePorn", subreddit, _title, _post_url, _imageURL)
c.execute(insert, data_value)
cnx.commit()
c.close()
cnx.close()
dataEntry("fake", "fake", "fake", "fake")
我收到了这个错误。
mysql.connector.errors.ProgrammingError: 1146 (42S02): Table 'sytykr.subredditname' doesn't exist
这让我相信我不能这样做,因此我想问如何做到最终可以传入表的变量名,而不是每次都硬编码。
cnx.escape_string()
转义)表名连接起来。 - Conspicuous Compiler