Python pyodbc 插入 sql
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20199569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pyodbc insert into sql
提问by daniel
I use a MS SQL express db. I can connect and fetch data. But inserting data does not work:
我使用 MS SQL express 数据库。我可以连接并获取数据。但是插入数据不起作用:
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.
在 MS SQL Server Management Studio 中,插入确实有效。
采纳答案by user151019
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.
您需要提交数据。每个 SQL 命令都在一个事务中,必须提交事务才能将事务写入 SQL Server,以便其他 SQL 命令可以读取它。
Under MS SQL Server Management Studio the default is to allow auto-commit which means each SQL command immediately works and you cannot rollback.
在 MS SQL Server Management Studio 下,默认设置是允许自动提交,这意味着每个 SQL 命令都会立即生效并且您无法回滚。
The insert example in the pyodbc Getting Started documentis
pyodbc 入门文档中的插入示例是
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.
注意对 cnxn.commit() 的调用。您必须调用 commit 否则您的更改将丢失!当连接关闭时,任何挂起的更改都将回滚。这使得错误恢复非常容易,但您必须记住调用 commit。

