Python 在破坏一个巨大的xml文件后插入数据库的有效方法

Python 在破坏一个巨大的xml文件后插入数据库的有效方法,python,Python,我需要拆分一个巨大的xml文件并 那么,这是我做的最有效的方法吗 这是我的密码 import xml.etree.cElementTree as etree filename = r'D:\test\Books.xml' context = iter(etree.iterparse(filename, events=('start', 'end'))) _, root = next(context) books = [] for event, elem in context: if ev

我需要拆分一个巨大的xml文件并 那么,这是我做的最有效的方法吗

这是我的密码

import xml.etree.cElementTree as etree
filename = r'D:\test\Books.xml'
context = iter(etree.iterparse(filename, events=('start', 'end')))
_, root = next(context)
books = []
for event, elem in context:
    if event == 'start' and elem.tag == '{http://www.book.org/Book-19200/biblography}Book':
        etree.register_namespace("", "http://www.book.org/Book-19200/biblography")
        xml = etree.tostring(elem)
        xmls.append(xml)
        if len(xmls) == 100:
            populate_db(books)
            books = []
        root.clear()

def populate_db(books):
    c.executemany('INSERT INTO Books VALUES (?)', books)
我的sample book.xml如下所示

<Books>
    <Book xmlns="http://www.book.org/Book-19200/biblography"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    ISBN="519292296"
    xsi:schemaLocation="http://www.book.org/Book-19200/biblography ../../book.xsd 
    http://www.w3.org/2000/12/xmldsig# ../../xmldsig-core-schema.xsd">
        <Detail ID="67">
            <BookName>Code Complete 2</BookName>
            <Author>Steve McConnell</Author>
            <Pages>960</Pages>
            <ISBN>0735619670</ISBN>        
            <BookName>Application Architecture Guide 2</BookName>
            <Author>Microsoft Team</Author>
            <Pages>496</Pages>
            <ISBN>073562710X</ISBN>
        </Detail>
    </Book>
    <Book xmlns="http://www.book.org/Book-19200/biblography"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    ISBN="519292296"
    xsi:schemaLocation="http://www.book.org/Book-19200/biblography ../../book.xsd 
    http://www.w3.org/2000/12/xmldsig# ../../xmldsig-core-schema.xsd">
        <Detail ID="87">
            <BookName>Rocking Python</BookName>
            <Author>Guido Rossum</Author>
            <Pages>960</Pages>
            <ISBN>0735619690</ISBN>
            <BookName>Python Rocks</BookName>
            <Author>Microsoft Team</Author>
            <Pages>496</Pages>
            <ISBN>073562710X</ISBN>
        </Detail>
    </Book>
</Books>

这种方法是添加到列表并使用100个批并插入到数据库中的有效方法,还是我需要在这里考虑多线程?这取决于XML文件的大小。兆字节还是兆字节

无论如何,解析XML文件很可能比插入DB要花更多的时间,所以不要过度设计它。只要试一下你的代码就可以了


记住:过早优化是万恶之源。

我的文件大约是2GbAs,我说过了,去做吧。根据您的示例数据,您将拥有大约300万个DB条目,这不应该挑战现代DB引擎。另外,听起来你不会一遍又一遍地运行这个程序,那么你为什么这么在乎运行时间呢?如果你问这个问题的时候就开始了,那么它已经完成了。那么在多个线程中进行解析有意义吗?如果是的话,我如何在多个线程中解析它呢?Hi Christian性能很重要,因为我必须插入300多个这样的文件。目前数据库已关闭,所以我正在等待运行它,看看需要多长时间拿。当您将代码转换为使用线程并使其停止崩溃时,如果您只是运行它,转换已经完成。