我正在解析XML并尝试将其值插入mysql数据库。(我只从typename开始)
XML看起来像:
<collection shelf="New Arrivals">
<movie title="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title="Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
我的代码如下:
# Print detail of each movie.
for movie in movies:
print ("*****Movie*****")
if movie.hasAttribute("title"):
print ("Title: %s" % movie.getAttribute("title"))
titleName = movie.getAttribute("title")
with con:
cur = con.cursor()
cur.execute("INSERT INTO Writers(Name) VALUES('Enemy Behind')")
type = movie.getElementsByTagName('type')[0]
print ("Type: %s" % type.childNodes[0].data)
with con:
typeName = type.childNodes[0].data
cur=con.cursor()
cur.execute("INSERT INTO Writers(type) VALUES(typeName)")
format = movie.getElementsByTagName('format')[0]
print ("Format: %s" % format.childNodes[0].data)
rating = movie.getElementsByTagName('rating')[0]
print ("Rating: %s" % rating.childNodes[0].data)
description = movie.getElementsByTagName('description')[0]
print ("Description: %s" % description.childNodes[0].data)
我得到错误:
Title: Enemy Behind
Traceback (most recent call last):
File "C:/....MyPython.py", line 35, in <module>
cur.execute("INSERT INTO Writers(type) VALUES(typeName)")
File "C:\Python34\lib\site-packages\MySQLdb\cursors.py", line 220, in execute
Type: War, Thriller
是否有人可以帮助我找出问题所在?我完全是新手,所以我完全迷失了
答案 0 :(得分:0)
# Closing the redirected text files.
sys.stdout.close()
sys.stderr.close()
# Defining the paths for the temp folder and the existing text files.
folder = args.directory + "\\" + "temp"
stdoutPath = folder + "\\" + "stdout.txt"
stderrPath = folder + "\\" + "stderr.txt"
# Deleting the text files first, then deleting the entire temporary folder.
os.remove(stdoutPath)
os.remove(stderrPath)
os.rmdir(folder)
类型中有一个空格。尝试将此行更改为
War, Thriller
到cur.execute("INSERT INTO Writers(type) VALUES(typeName)")
要在查询中包含cur.execute("INSERT INTO Writers(type) VALUES('typeName')")
以包含typeName。
示例强>
假设类型为''
,char
等
此SQL varchar
将失败,因为我们插入的字符串值未用引号括起来。
然而,
insert into Writers(type) values(my string)
应该有效,因为我们用引号括起了我们插入的字符串值。