实际上,我想编写一些Python代码以将数据放入SQL中 数据库,为此,我编写了一个示例Python脚本只是为了测试它是否 作品。查询不起作用,什么也没有发生。我知道一定有 我缺少的东西。
import pyodbc
import xml.sax
class Parser(xml.sax.ContentHandler):
def __init__(self):
self.current_tag = ""
self.title = ""
self.type = ""
self.format = ""
self.year = ""
self.rating = ""
self.stars = ""
self.description = ""
def startElement(self, tag, attribute):
self.current_tag = tag
if tag == "movie":
self.title = attribute['title']
def endElement(self, tag):
if tag == 'movie':
conn = pyodbc.connect('Driver={SQL Server};'
'Server=localhost;'
'Database=Datawarehouse_project;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('insert into Movies values (?,?,?,?,?,?,?)', (self.title, self.type, self.format, self.year,
self.rating, self.stars, self.description))
def characters(self, content):
if self.current_tag == "type":
self.type = content
elif self.current_tag == "format":
self.format = content
elif self.current_tag == "year":
self.year = content
elif self.current_tag == "rating":
self.rating = content
elif self.current_tag == "stars":
self.stars = content
elif self.current_tag == "description":
self.description = content
if __name__ == '__main__':
parser = xml.sax.make_parser()
handler = Parser()
parser.setContentHandler(handler)
parser.parse('movies.xml')
代码将运行且不执行任何操作。我希望这段代码可以简单地从XML文件“ movies.xml”中获取数据,并将数据放入数据库“ Datawarehouse_project”中的表Movies中。
答案 0 :(得分:0)
查询后我错过了conn.commit(),但是仍然无法正常工作。原因可能是我无法在endElement()内访问查询中的值