pyodbc插入sq

2024-09-29 21:31:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用MS SQL express数据库。我可以连接和获取数据。但插入数据不起作用:

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

我没有错误,但是没有任何东西被插入到表中。 在获取数据之后,将直接获取插入的行。但什么也救不了。

在MS SQL Server管理工作室中,插入确实有效。


Tags: 数据test数据库messageexecutesqlcursorms
1条回答
网友
1楼 · 发布于 2024-09-29 21:31:32

你需要提交数据。每个SQL命令都在一个事务中,必须提交该事务才能将该事务写入SQL Server,以便其他SQL命令可以读取该事务。

在mssqlservermanagementstudio下,默认设置是允许自动提交,这意味着每个SQL命令都可以立即工作,并且不能回滚。

pyodbc Getting Started document中的插入示例是

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

或者更好地使用参数

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

正如文件所说

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.

相关问题 更多 >

    热门问题