pyodbc insert into sql

烂漫一生 提交于 2019-12-17 22:36:04

问题


I use a MS SQL express db. I can connect and fetch data. But inserting data does not work:

cursor.execute("insert into [mydb].[dbo].[ConvertToolLog] ([Message]) values('test')")

I get no error but nothing is inserted into the table. Directly after I fetch the data the inserted row is fetched. But nothing is saved.

In MS SQL Server Management Studio the insertion does work.


回答1:


You need to commit the data. Each SQL command is in a transaction and the transaction must be committed to write the transaction to the SQL Server so that it can be read by other SQL commands.

Under MS SQL Server Management Studio the default is to allow auto-commit which means each SQL command immediately works and you cannot rollback.

The insert example in the pyodbc Getting Started document is

cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()

or better using parameters

cursor.execute("insert into products(id, name) values (?, ?)", 'pyodbc', 'awesome library')
cnxn.commit()

As the document says

Note the calls to cnxn.commit(). You must call commit or your changes will be lost! When the connection is closed, any pending changes will be rolled back. This makes error recovery very easy, but you must remember to call commit.



来源:https://stackoverflow.com/questions/20199569/pyodbc-insert-into-sql

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