使用变量

时间:2017-05-27 01:38:38

标签: python sql python-3.x sqlite

我有一个包含列'id','title','name'的表,我正在尝试根据解析的XML with Beautiful Soup将值插入其中。跟踪每个值的去向的函数由:

定义
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

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:0)

似乎在Python中处理变量的方式存在问题。奇怪的是,用(?)替换%s修复了它。所以这个:

def getmax(column):
    query = 'select count(%s) from longform' % column
    c.execute(query)
    result = c.fetchall()
    for e, i in enumerate(result):
        for y in enumerate(i):
            if not y[1]:
                return 0
            else:
                return y[1]

有效,而问题中发布的getmax版本并不适用。很想知道原因。