我在第一次迭代中使用此代码获得TypeError: cannot serialize ('John',) (type tuple)
。为什么SELECT name FROM potluck
输出'John',
而不是'John'
?
('John',)
('Sandy',)
('Tom',)
('Tina',)
无论如何,我不知道问题是否存在。
#!/usr/bin/env python
import psycopg2
import sys
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
con = None
try:
con = psycopg2.connect(database='events', user='demo')
cur = con.cursor()
cur.execute("SELECT name FROM potluck")
rows = cur.fetchall()
top = Element('top')
for row in rows:
#print row
comment = Comment('Generated test')
top.append(comment)
child = SubElement(top, 'child')
child.text = row
print tostring(top)
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
答案 0 :(得分:1)
试试这个:
child.text = row[0]
元素的文本字段通常是单个字符串。
参考:http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.text