Python mysql-connector multi insert not working?

风格不统一 提交于 2020-12-06 06:27:07

问题


I just started using the Mysql Connector library for Python and I seem to be running into an issue I can't get my head around.

I have Python dynamically generate Insert statements to be executed on MySQl database.

I batch them together in one string and then I execute every n together in the one cusrsor.execute() statement however for some reason when I check the DB and table, the new rows are nowhere to be found.

I tried it with even just two insert statements together and they still didn't get persisted to the DB even though I call execute, call a commit and then close the cursor and connection in that order.

If I have just one insert statement in the execute command and I remove the multi flag then it works fine.

Does anyone know why this could be happening?

Sample code:

from mysql import connector
my_sql_connection = connector.connect(user='user', password='pass',
                                              host='hostname',
                                              database='db')
mysql_cursor = my_sql_connection.cursor()

statement = "Insert into table (col) values (1); Insert into table (col) values (2);"

mysql_cursor.execute(statement, multi=True)
my_sql_connection.commit()
mysql_cursor.close()
my_sql_connection.close()

After this code is called, there are no errors however no new rows show up in the table.


回答1:


You should try using executemany instead of execute with the multi flag, it's generally much simpler to implement.

Also,I would recommend you switch to PyMySQL, it has a very complete documentation and from my experience works much better 'out of the box' than the mysql connector library.



来源:https://stackoverflow.com/questions/33745270/python-mysql-connector-multi-insert-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!