简体   繁体   中英

How to insert large list data into MySQL table using Python SQL.Connector

data = [
    {"question": "How old was Harry?", "options": ["10", "20", "none of the above"], "answer": "10"},
    {"question": "example question", "options": ["1", "2", "3"], "answer": "1"},
]

mycursor.execute("INSERT INTO userinfo VALUES ('{}','{}','{}');".format("1234", "test", data))
my_database.commit()

I used the above lines of code to commit the changes but the Interpreter,Throws an error like

_mysql_connector.MySQLInterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'question': 'How old was Harry?', 'options': ['10', '20', 'none of the above'], '' at line 1

and at the SQL Table, I have assigned 3 Columns (eid(VARCHAR(6)),ename(VARCHAR(10)),questions(BLOB) .

How can I solve this error?

Put all the values being inserted into a list of tuples. Then use a parametrized query along with cursor.executemany() .

params = [("1234", "test", d["question"]) for d in data]

mycursor.executemany("INSERT INTO userinfo VALUES (%s,%s,%s);", params)
my_database.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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