微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用变量替换表名使用python和mysql连接器

如何解决用变量替换表名使用python和mysql连接器

显示MysqL连接器的异常是告诉您该表在您的数据库中不存在。

另外,您尝试使用“ MachinePorn”作为参数,但未在查询中定义它,而是将其硬编码为“ subredditName”。

我认为您应该在查询中将数据库定义为另一个参数,它将正常运行:

def dataEntry(subreddit, _title, _post_url, _imageURL):
     cnx = MysqL.connector.connect(**config)

     c = cnx.cursor()
     insert = cnx.escape_string("INSERT INTO MachinePorn (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")

解决方法

我想动态更改插入数据的表的变量名。

这目前有效,

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

    data_value = (subreddit,_imageURL)

    c.execute(insert,data_value)
    cnx.commit()
    c.close()
    cnx.close()

dataEntry("fake","fake","fake")

但是,当我尝试对表名(在这种情况下为“ FoodPorn”)执行相同操作时,对于动态表(如本例中的MachinePorn),

def dataEntry(subreddit,_imageURL):
    cnx = mysql.connector.connect(**config)

    c = cnx.cursor()
    insert = ("""INSERT INTO subredditName
                    (subreddit,%s)""")

    data_value = ("MachinePorn",subreddit,"fake")

我得到这个错误,

mysql.connector.errors.ProgrammingError: 1146 (42S02): Table 'sytykr.subredditname' doesn't exist

这使我相信我无法通过这种方式执行操作,因此我想问一下如何执行该操作,以便最终可以在表中传递变量名,而不必每次都对其进行硬编码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。