Jiamei
Jiamei

Reputation: 445

How to use Pyodbc to read in SQL results generated from joining 2 CTE's from 2 databases

I have a SQL script that joins two CTE's together, one CTE is from database1 and another CTE is from database2. It can be run successfully in SQL Server.

However, I'd like to establish a connection between the SQL Server to Python using pyodbc package (like below) so that I can read-in the results directly. Since we can only specify one database in the following code, how do I establish the connection if my SQL script contains two different databases?

conn = pyodbc.connect('Driver= {SQL Server Native Client 11.0};'
                      'Server= server;'
                      'Database = database1;'
                      'InitialCatalog=dbo;'
                      'Trusted_Connection=yes;')

query = open(file_path, 'r') 
df = pd.read_sql_query(query.read(), conn)
query.close() 

Upvotes: 0

Views: 203

Answers (0)

Related Questions