python - 使用变量查询时 UPDATE TABLE 返回空值

标签 python sql python-3.x sqlite

我有一个包含“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/

相关文章:

python-3.x - 如何使用 Amazon S3 下载 Landsat 8 图像

python - 如何将不同形状的np数组组合在一起并按行分开

python - Spyder python : Skip printing all code when using "run current cell"

php - 选择第二、第三、第四、第五最大的数

python-3.x - mode = 'w' 仅适用于logging.FileHandler,但不适用于logging.handlers.RotatingFileHandler

python-3.x - BlockBlobService 类位于 Python Azure 模块中的什么位置?

python - 如何使用异步理解?

javascript - 从 javascript 函数生成 django HTML URL

sql - 从sql表中提取行数

mysql - 使用存储过程计算团队中的人数