My config file has database details like below:
config = configparser.ConfigParser()
config.read("C:/configsql.ini")
_SERVER_NAME = config['SQL']['SERVER_NAME']
_DATABASE = config['SQL']['DATABASE']
_USERNAME = config['SQL']['USERNAME']
_PASSWORD = config['SQL']['PASSWORD']
How do I utilize _DATABASE variable in my SQL Queries which are executed via python. Currently, SQL queries are hardcoded with database name - TEST.
Below are two types of SQL Queries used in my python code:
connsql = self.sql_connection()
query = "select distinct top 2 filing_id, StatusIndicator from [TEST].[dbo].[FILE] where ID = ?"
resultset = connsql.cursor().execute(query,values).fetchall()
connsql.cursor().commit()
connsql.close()
And,
query ='''
IF EXISTS(select [file_name], [file] from [TEST].[dbo].[FILE] where ID = ? and TypeID = 1)
BEGIN
select [file_name], [file] from [TEST].[dbo].[FILE] where ID = ? and TypeID = 1
END
ELSE
BEGIN
SELECT - 1
END
'''
values = (Id,Id)
results = connsql.cursor().execute(query, values).fetchall()
asked Dec 13, 2019 at 21:54
user2961127
1,1835 gold badges21 silver badges33 bronze badges
1 Answer 1
How do I utilize _DATABASE variable in my SQL Queries which are executed via python.
You should normally specify the database in your sql_connection, so you can use 2-part names instead of 3-part names in your queries.
answered Dec 13, 2019 at 22:25
David Browne - Microsoft
90.8k7 gold badges53 silver badges87 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default
query =" "But, how to make it work for second query format where it has 3 quotesquery =''' '''