首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mysql表名获取不需要的引号结果表不存在错误

Mysql表名获取不需要的引号结果表不存在错误
EN

Stack Overflow用户
提问于 2021-09-26 20:12:55
回答 1查看 29关注 0票数 0
代码语言:javascript
复制
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")

我有上面的代码,并给出了下面的错误:

代码语言:javascript
复制
Failed to insert into MySQL table 1146 (42S02): Table 'fx003.'aud-cad_30mins'' doesn't exist

aud-cad_30mins表确实存在,并且如下所示的insert查询正在执行其工作:

代码语言:javascript
复制
mySql_insert_query = """INSERT INTO aud-cad_30mins (date, trend) VALUES ( "2021-09-24 21:00:00","Short"  )""" 

因此,当我尝试在查询中使用变量时,它会给出错误。为什么表名会被不需要的引号引用?检查了几个教程,但没有找到解决方案,有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-26 20:24:38

表名应该硬编码在查询字符串中,而不是作为占位符%s,这意味着要插入的值。因此,如果变量中有表名,则可以在调用cursor.execute()之前通过format()替换它

代码语言:javascript
复制
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO {} (date, trend) VALUES ( %s, %s )""".format(dbtable)

请参阅示例in the docs

编辑:正如比尔在评论中提到的那样,不要在%s占位符周围添加反引号。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69338610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档