简体   繁体   English

Python 导入 XML 介绍 SQLITE (xmltodict)

[英]Python import XML intro SQLITE (xmltodict)

I'm trying to parse an XML file and import it into an SQLITE database.我正在尝试解析 XML 文件并将其导入 SQLITE 数据库。

the XML looks like this: XML 如下所示:

<resultset>
    <row>
        <column name="pct_lucru">unit name</column>
        <column name="cod_comercial">00032749</column>
        <column name="denumire_med">stuff name</column>
        <column name="producator">fabri</column>
        <column name="tip_produs">koops</column>
        <column name="tva">24.000000</column>
        <column name="umc">1</column>
        <column name="furnizor">FURNIZORI DIVERSI</column>
        <column name="data_expirarii">2015-12-31</column>
        <column name="lot">80063</column>
        <column name="cant_fl">1</column>
        <column name="fractie">0</column>
        <column name="cantitate">1</column>
        <column name="pret_intr">62.930000</column>
        <column name="val_intr">62.930000</column>
        <column name="pret_fl">82.720000</column>
        <column name="valoare">82.720000</column>
    </row>
</resultset>

And I have the following python code我有以下python代码

import xmltodict
import sqlite3

conn = sqlite3.connect("test.sqlite")
c = conn.cursor()

with open("export.xml") as fd:
    obj = xmltodict.parse(fd.read())

for row in obj["resultset"]["row"]:
    for column in row["column"]:
        c.execute("INSERT INTO stocks ? VALUES '?'", [column["@name"], column["#text"]])
    print "item inserted \n"

Which produces the following error产生以下错误

Traceback (most recent call last):
        File "dbimport.py", line 12, in <module>
            c.execute("INSERT INTO stocks ? VALUES '?'", [column["@name"], column["#text"]])
sqlite3.OperationalError: near "?": syntax error

What am I doing wrong here?我在这里做错了什么? I've used this method before and it worked just fine, albeit not with XML files.我以前使用过这种方法,它工作得很好,尽管不适用于 XML 文件。

The ? ? can only be used for values, not for column names.只能用于值,不能用于列名。 This这个

INSERT INTO stocks ? VALUES '?'

is not valid.无效。 You must use你必须使用

INSERT INTO stocks (columnname) VALUES (?)

Note the missing quotes around the ?注意?周围缺少的引号. . In code:在代码中:

c.execute("INSERT INTO stocks ({}) VALUES (?)".format(column["@name"]), column["#text"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM