首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用变量替换表名。使用python和mysql连接器

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

Stack Overflow用户
提问于 2014-10-12 12:14:22
回答 1查看 7.8K关注 0票数 3

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

目前这是可行的,

代码语言:javascript
复制
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 ),

代码语言:javascript
复制
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")

我知道这个错误,

代码语言:javascript
复制
mysql.connector.errors.ProgrammingError: 1146 (42S02): Table 'sytykr.subredditname' doesn't exist

这让我相信我不能这样做,所以我想问我怎么做,这样我最终可以在表中传递一个变量名,而不是每次都要硬编码。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-11 23:55:30

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

此外,您试图使用'MachinePorn‘作为参数,但是您没有在查询中定义它,而是硬编码的'subredditName’。

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

代码语言:javascript
复制
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")
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26324996

复制
相关文章

相似问题

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