I am a newbie so please bear with me. I am trying to do a very simple insert from Python into a MS SQL database. I have tried pure pyodbc resulting in "pyodbc.ProgrammingError: No results. Previous SQL was not a query.":
import pyodbc
server = 'server'
database = 'db'
username = 'user'
password = 'pswd'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
query = "SET NOCOUNT ON INSERT INTO foo ([x],[y],[z]) VALUES(1,1,1) "
cursor.execute(query)
row = cursor.fetchone()
while row:
print (row)
row = cursor.fetchone()
And I have tried a combination of sqlalchemy, pyodbc and pandas resulting in "sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically."
import sqlalchemy
import pyodbc
import urllib
import pandas as pd
server = 'server'
database = 'db'
username = 'user'
password = 'pswd'
driver= '{ODBC Driver 17 for SQL Server}'
params = urllib.parse.quote_plus('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
sql = "SET NOCOUNT ON INSERT INTO foo ([x],[y],[z]) VALUES(1,1,1)"
sql_df = pd.read_sql(sql=sql, con = engine)
I have tried playing around with SET NOCOUNT ON, putting the code into a stored procedure and calling the procedure and all kinds of other combinations. Nothing seems to work.
I would greatly appreciate any help. Thank you.