I have several SQL statements (update
, delete
, insert
,...) in my Python code and all of them refer to one database. Now I want to pass the database name as a variable to my query so that I can change the database name one time in my code instead of manually updating the database name everywhere in SQL statements and also connection strings.
How can I pass Database name as a parameter to both SQL statement and connection string? for example in this code I want to pass DBNAME to connection string and SQL query instead of using the database name which is mainDB.
import pyodbc
DBNAME='mainDB'
cn = pyodbc.connect ( 'Driver={SQL Server};'
'Server=myserver;'
'Port=1433'
'Database=mainDB;'
'Trusted_Connection=yes;')
cursor = cn.cursor()
SQLquery = """ SELECT distinct [ID],[NAME]
FROM [mainDB].[dbo].[customer]
"""
cursor.execute(SQLquery)
for row in cursor:
print (row)
break