AttributeError: 'pymssql.Cursor' object has no attribute 'commit'
时间: 2023-08-15 21:05:45 浏览: 421
对不起,我之前给出的回答中有误。实际上,`pymssql.Cursor` 对象没有 `commit` 方法。在 `pymssql` 中,提交事务的操作是通过数据库连接对象来完成的。
以下是使用 `pymssql` 将数据插入数据库并提交事务的正确示例:
```python
import pymssql
conn = pymssql.connect(server='服务器名称', user='用户名', password='密码', database='数据库名称')
cursor = conn.cursor()
sql = "INSERT INTO 表名 (列1, 列2, 列3) VALUES (%s, %s, %s)"
values = ('值1', '值2', '值3')
cursor.execute(sql, values)
conn.commit()
cursor.close()
conn.close()
```
请注意,事务的提交是通过调用数据库连接对象 `conn` 的 `commit()` 方法实现的,而不是 `cursor` 对象。在执行完所有数据库操作后,使用 `conn.commit()` 来提交事务。
对于 `pymssql`,另外一个事务的自动提交设置是可选的,默认情况下事务会自动提交。如果你希望手动控制事务的提交和回滚,可以将 `autocommit` 属性设置为 `False`:
```python
conn.autocommit(False)
```
这样,你需要在适当的时候调用 `conn.commit()` 来手动提交事务,并通过 `conn.rollback()` 来回滚事务。
阅读全文
相关推荐

















