2

我正在尝试解析 XML 文件并将其导入 SQLITE 数据库。

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>

我有以下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"

这会产生以下错误

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

我在这里做错了什么?我以前使用过这种方法,它工作得很好,虽然不是 XML 文件。

4

1 回答 1

2

?只能用于值,不能用于列名。这个

INSERT INTO stocks ? VALUES '?'

无效。你必须使用

INSERT INTO stocks (columnname) VALUES (?)

注意周围缺少的引号?。在代码中:

c.execute("INSERT INTO stocks ({}) VALUES (?)".format(column["@name"]), column["#text"])
于 2015-06-19T08:13:27.143 回答