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

I would like to dynamically change the variable name of the table I insert data into.

This currently works,

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

but when I try and do the same for the table name in this case "FoodPorn", but for a dynamic one such as in this example 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")

I get this error,

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

This leads me to believe I cannot do it this way and so I would like to ask How can I do it so I can eventually pass a variable name in of the Table, instead of having to hard code it each time.

解决方案

The exception that is showing mysql connector is telling you that the table doesn't exist in your database.

In addition, you're trying to use 'MachinePorn' as the argument but you didn't define that in the query, it's hardcoded 'subredditName'.

I think you should define database as another parameter in the query and it will run fine:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值