【问题标题】:PyPyODBC not inserting record to MS-SQL serverPyPyODBC 未将记录插入 MS-SQL 服务器
【发布时间】:2017-02-22 12:39:22
【问题描述】:

我是 Python 新手,编写了这个简单的代码来将数据插入 SQL 服务器:

import pypyodbc
connect = pypyodbc.connect('Driver={Sql Server Native Client 11.0};Server=.;Database=SAMPLE;Trusted_Connection=yes;')
cursor = connect.cursor()
print('Trying to insert!')
cursor.execute("insert into [SAMPLE].[dbo].[Register] VALUES ('behzad','razzaqi')")
print('Insert Finish!')
connect.close()

代码执行得很好,甚至我Insert Finish!,但是当我检查 SQL Server 时,没有插入任何记录。发生了什么?我该如何解决这个问题?

【问题讨论】:

  • 您需要执行cursor.commit() 以反映更改!
  • 可能和所有 SQL 数据库一样:在关闭连接之前提交。

标签: python sql-server pypyodbc


【解决方案1】:

我相信您也必须致电connect.commit()。试试:

import pypyodbc
connect = pypyodbc.connect('Driver={Sql Server Native Client 11.0};Server=.;Database=SAMPLE;Trusted_Connection=yes;')
cursor = connect.cursor()
print('Trying to insert!')
cursor.execute("insert into [SAMPLE].[dbo].[Register] VALUES ('behzad','razzaqi')")
connect.commit()
print('Insert Finish!')
connect.close()

【讨论】:

  • @chertchertopert,谢谢,很高兴为您提供帮助
  • 享受您的新投票特权 :)
  • @apomene 得到了来自数据库新手的免费投票(我知道下次我会将其标记为重复)
  • @Jean-FrançoisFabre,谢谢,我很感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多