1
$\begingroup$

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
$\endgroup$
1
  • $\begingroup$ Couldn't you just pass the DBNAME variable itself (rather mainDB) in the connection string and sql query? Or I do not understand the question. $\endgroup$ Aug 5, 2018 at 8:46

0

Browse other questions tagged or ask your own question.