0

I am able to write to the db when connecting outside of the function but unable to write to the database when calling it via the function

    def Metric_Insert():
     cnxn1 = pyodbc.connect('DRIVER='+driver+';SERVER='+SERVER+';PORT=1433;DATABASE='+DATABASE+';UID='+username+';PWD='+ pwd)
     cursor = cnxn1.cursor()
     #print("Connected in Metric_Insert")
     sql9='''Insert into Stage.CBO_Detail_Person(File_Master_ID,Person_CUID,
                            Family_ID,Age,Metric) Values (?,?,?,?,?);'''
     Val9=(File_Master_ID[0],Person_CUID[0],Family_ID[0],'Age','xyz')
     cursor.execute(sql9,Val9)
     cnxn1.commit()
     #print("Connected in Metric_Insert")
     #return
  Metric_Insert()
RB17
  • 356
  • 1
  • 8
  • 26
  • Where are all your variables used to connect to the database defined? If that is all your code the function will not know what ```driver```, ```SERVER```, ```DATABASE``` ```username```, ```pwd``` or any other variables not defined within the function are. What is the error printing out? – WK123 Apr 30 '20 at 18:33
  • The variables are defined globally. I am not getting any error. I am able to connect and insert records just outside the function. – RB17 Apr 30 '20 at 18:36
  • I'd try to implement a try and except block to see what is going on. I always try to have a separate function for returning a database connection as well because the connection may not be being established at all in this code and that could be the problem https://www.w3schools.com/python/python_try_except.asp – WK123 Apr 30 '20 at 18:44
  • Please fix indentation (very important in Python) and advise if this function is not nested within another function or class object or as a module called from another script. We need more context. See [What does if __name__ == “__main__”: do?](https://stackoverflow.com/q/419163/1422451) – Parfait Apr 30 '20 at 19:15
  • It worked only after I defined the function globally. Not just outside the block I was calling the function from. @Parfait, I don't think it was because of indentation – RB17 May 03 '20 at 05:48
  • Please show how parent function calls this function. See [mcve]. – Parfait May 03 '20 at 15:19
  • @Parfait The same way as shown in my question. Already got it resolved by defining the function globally – RB17 May 03 '20 at 17:05

0 Answers0