Good day!

There are variables in the script code:

HOST = '127.0.0.1' DBASE = 'disp' USER = 'cpps' PASS = '123' 

How can I pass variable values ​​to a procedure?

This option does not work

 conn = pyodbc.connect("DRIVER={SQL Server};SERVER=HOST;UID=cpps;PWD=123;DATABASE=disp") 

This also works on

 conn = pyodbc.connect("DRIVER={SQL Server};SERVER=$HOST;UID=cpps;PWD=123;DATABASE=disp") 

thank

  • I have implemented conn = pyodbc.connect ("DRIVER = {SQL Server}; SERVER = localhost; UID = cpps; PWD = 123; DATABASE = disp") and just thought that you can substitute the value of a variable in the parameter string by name - Ivan Babintsev
  • I apologize, misunderstood the question first - I updated my answer. - qnub
  • I fixed it again :) - qnub

2 answers 2

Parameters are passed in a string variable? Then you can:

 HOST = '127.0.0.1' DBASE = 'disp' USER = 'cpps' PASS = '123' conn = pyodbc.connect("DRIVER={SQL Server};SERVER=%(HOST)s;UID=%(USER)s;PWD=%(PASS)s;DATABASE=%(DBASE)s" % {'HOST':HOST, 'DBASE': DBASE, 'USER': USER, 'PASS': PASS}) 

    You can use the locals() construct:

     HOST = '127.0.0.1' DBASE = 'disp' USER = 'cpps' PASS = '123' dsn = "DRIVER={SQL Server};SERVER=%(HOST)s;UID=%(USER)s;PWD=%(PASS)s;DATABASE=%(DBASE)s" % locals() 

    Or the same with string.format()

     dsn = "DRIVER={{SQL Server}};SERVER={HOST};UID={USER};PWD={PASS};DATABASE={DBASE}".format(**locals()) print(dsn) # 'DRIVER={SQL Server};SERVER=127.0.0.1;UID=cpps;PWD=123;DATABASE=disp'