How to execute a multiline SQL query from a file in python

200 Views Asked by At

I am writing a python script that accesses a database and needs to fetch some data. I have an .sql file with a multiline SELECT statement, which I checked in SQL Management Studio; it executes correctly. When I try to get python to read the .sql file it seems to not fetch any data. I tried executing some other SQL from a file containing just a single-line query like: SELECT * FROM table_1, and it executes just fine. Additionally if i just store the SQL query inside the Python script as a string, and add "'''" to the start and the end of the string it runs alright as well.

How can I fix this? Below is my current python script and the output it generates, unfortunately I cannot share the sql file, but as I mentioned it executes correctly. This script is supposed to run on both Windows and Linux machines.

Test.PY:

import pymssql

#Database Info
server = 'DatabaseServer\\instance'
database = 'DB'
username = r'ad\login'
password = r'password'

#SQL Query File
sql_query_file = 'query.sql'

try:
    with open(sql_query_file, 'r') as query_file:
        sql_query = query_file.read()

    conn = pymssql.connect(server=server, user=username, password=password, database=database)

    cursor = conn.cursor()

    cursor.execute(sql_query)

    result = cursor.fetchall()
    for row in result:
        print(row)

    conn.commit();
except Exception as e:
    print("Error: ", e)

finally:
    if cursor:
        cursor.close
    if conn:
        conn.close

Output (is fully empty):

C:\Users\...>python test.py

C:\Users\...>

Thanks for all the help in advance.

0

There are 0 best solutions below