【问题标题】:INSERT query is not executing from the python listing but executes pretty fine from MSSQL Management studioINSERT 查询未从 python 列表执行,但从 MSSQL Management Studio 执行得很好
【发布时间】:2017-12-11 22:58:56
【问题描述】:

我正在尝试使用 python 中的 pypyodbc 库对 MSSQL Server 执行一个简单的 INSERT 查询。 如果我尝试执行

SELECT Country, City, Street, House, Zipcode, Date FROM postal_test_db.dbo.addresses

从 Microsoft SQL Management Studio 中它可以正确执行,就像我从我的 python 代码中执行它一样:

import pypyodbc
connection_string ='Driver={SQL Server};Server=PC\TEW_SQLEXPRESS;Uid=py_test_user;Pwd=1q2w3e4r5t!A;'
connection = pypyodbc.connect(connection_string)
SQL = "SELECT Country, City, Street, House, Zipcode, Date FROM postal_test_db.dbo.addresses"
cur = connection.cursor()
result = cur.execute(SQL)
print(result.fetchone())

cur.close()
connection.close()

但如果我尝试从 Microsoft SQL Management Studio 执行下一个代码:

INSERT INTO postal_test_db.dbo.addresses (Country, City, Street, House, Zipcode) `VALUES ('Россия', 'Ульяновск', 'Варейкиса', '25', '432035')`

那么它在管理工作室中仍然可以正常工作,但是应该执行相同操作的 python 代码无法执行

import pypyodbc
connection_string ='Driver={SQL Server};Server=PC\TEW_SQLEXPRESS;Uid=py_test_user;Pwd=1q2w3e4r5t!A;'
connection = pypyodbc.connect(connection_string)
SQL = "INSERT INTO postal_test_db.dbo.addresses (Country, City, Street, House, Zipcode) VALUES ('Россия', 'Ульяновск', 'Варейкиса', '25', '432035')"
cur = connection.cursor()
result = cur.execute(SQL)
print(result.fetchone())

cur.close()
connection.close()

抛出下一个错误:

    pypyodbc.ProgrammingError: ('24000', '[24000] [Microsoft][ODBC SQL Server Driver
]Invalid cursor state')

the visual representation of the CMD window with the corresponding error message 我究竟做错了什么?我在 Management Studio 和 python 列表中以同一用户身份登录到 MSSQL,并且该用户拥有所有必要的权限(如果他没有 - 他将无法从 Management Studio 执行相同的代码 - 它是对我来说合乎逻辑)。

【问题讨论】:

  • print 行发生错误。 fetchone 是否在 INSERT 之后工作?
  • 不,row = cur.fetchone()) 紧跟在 result = cur.execute(SQL) 行之后不起作用并引发与 print(result.fetchone()) 相同的错误。

标签: python sql-server pypyodbc


【解决方案1】:

1) 你确定在exec 之后可以fetchone() 吗?您没有要求退货 2)如果您希望您的更改生效,您需要commit()

【讨论】:

    猜你喜欢
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    相关资源
    最近更新 更多