1

I am trying to execute a simple INSERT query to MSSQL Server using the pypyodbc library in python. If I try to execute

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

from the Microsoft SQL Management Studio it executes correctly as well as if I execute it from my python code:

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()

But if I try to execute next code from the Microsoft SQL Management Studio:

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

then it still works well from the management studio but the python code which is supposed to do the same fails to execute

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()

throwing the next error:

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

the visual representation of the CMD window with the corresponding error message What am I doing wrong? I a logging to MSSQL as the same user both in Management studio and in python listing and the user has all the necessary permissions (if he didn't had - he would not be able to execute the same code from the Management studio - it is logical for me).

1 Answers1

0

1) Are you sure you can fetchone() after exec? There is nothing you asked to return 2) You need to commit() if you want your changes to be effective

dgan
  • 1,349
  • 1
  • 15
  • 28