使用sax解析器时如何使用SQL查询

问题描述 投票:0回答:1

实际上我想编写一些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'中的表中。

sql-server python-3.x xml-parsing
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.