import mysql.connector
def add_features_to_db(stockname, timeframe, date, feature):
try:
conn = mysql.connector.connect(
user='root', password='', host='localhost', database='fx003')
cursor = conn.cursor()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO `%s` (date, trend) VALUES ( `%s`, `%s` )"""
record = (dbtable, date, feature)
cursor.execute(mySql_insert_query, record)
conn.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
add_features_to_db("aud-cad", "_30mins", "2021-09-24 21:00:00", "Short")我有上面的代码,并给出了下面的错误:
Failed to insert into MySQL table 1146 (42S02): Table 'fx003.'aud-cad_30mins'' doesn't existaud-cad_30mins表确实存在,并且如下所示的insert查询正在执行其工作:
mySql_insert_query = """INSERT INTO aud-cad_30mins (date, trend) VALUES ( "2021-09-24 21:00:00","Short" )""" 因此,当我尝试在查询中使用变量时,它会给出错误。为什么表名会被不需要的引号引用?检查了几个教程,但没有找到解决方案,有什么想法吗?
发布于 2021-09-26 20:24:38
表名应该硬编码在查询字符串中,而不是作为占位符%s,这意味着要插入的值。因此,如果变量中有表名,则可以在调用cursor.execute()之前通过format()替换它
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO {} (date, trend) VALUES ( %s, %s )""".format(dbtable)请参阅示例in the docs
编辑:正如比尔在评论中提到的那样,不要在%s占位符周围添加反引号。
https://stackoverflow.com/questions/69338610
复制相似问题