I try to put some informations from a XML file to

2019-08-26 10:48发布

When I try to put in a SQL database the subelement attribute and text, I get this:

Failed inserting record into python_users table 1054 (42S22): Unknown column 'a' in 'field list'".

SQL itself it's set with a table named "valoare" and 2 areas for values("moneda" & "flux")

for child in root:
    for element in child:
        for subelement in element:
            a = subelement.attrib["currency"]
            b = subelement.text
            connection = mysql.connector.connect(
                host="localhost",
                user="root",
                passwd="admin",
                database="python",
            )
            sql_insert_query = """ INSERT INTO valoare
                          (moneda, flux) VALUES (a, b)"""
            cursor = connection.cursor()
            result = cursor.execute(sql_insert_query)
            connection.commit()

标签: python mysql
1条回答
劳资没心,怎么记你
2楼-- · 2019-08-26 11:11

The actual error is caused by not using placeholders like you're supposed to.

Also, you really don't want to be reconnecting to the database like that for each element. In addition, you can only commit when everything's done:

connection = mysql.connector.connect(
    host="localhost", user="root", passwd="admin", database="python"
)
cursor = connection.cursor()

for child in root:
    for element in child:
        for subelement in element:
            a = subelement.attrib["currency"]
            b = subelement.text
            result = cursor.execute(
                "INSERT INTO valoare (moneda, flux) VALUES (%s, %s)", (a, b)
            )

connection.commit()
查看更多
登录 后发表回答