2017-05-27 42 views
1

我有一个列'id','title','name'的表,并且正试图根据与美丽的汤分析的XML插入值。当用变量查询时返回空值的UPDATE TABLE

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 

非常感谢您的帮助。

回答

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发布的问题没有。会很好奇知道为什么。