我有一个包含“id”、“title”、“name”列的表,并尝试根据使用 Beautiful Soup 解析的 XML 向其中插入值。跟踪每个值的去向的函数定义如下:
def getmax(column):
query = 'select count(?) from table'
c.execute(query, [column])
result = c.fetchall()
for e, i in enumerate(result):
for y in enumerate(i):
if not y[1]:
return 0
else:
return y[1] # used because fetchall returns a tuple
这给了我最后一行,其中为每列插入了一个值。插入值的函数如下所示:
for e in soup.findAll('title'):
e = str(e)
query = "insert into table (id, title) values (?, ?)"
c.execute(query, (getmax('title') + 1, e))
db.commit()
for e in soup.findAll('name'):
e = str(e)
query = "UPDATE table SET name = (?) WHERE id = (?);"
c.execute(query, (e, getmax('name') + 1))
db.commit()
这将返回:
id title name
1 title1
2 title2
3 title3
4 title4
5 title5
非常感谢您的帮助。
最佳答案
您可以使用format()
(有关详细信息,请参阅this)方法来解决此问题。此外,您可以使用a if condition else b
来简化代码:
def getmax(column):
query = 'select count({}) from longform'.format(column)
c.execute(query)
result = c.fetchall()
for e, i in enumerate(result):
for y in enumerate(i):
return y[1] if y[1] else 0
关于python - 使用变量查询时 UPDATE TABLE 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44212114/