简体   繁体   中英

Python MicrosoftSQL connection error using pandas and SQLAlchemy

I have a script that uses pandas to query a microsoft sql database and enter the results in an excel workbook.

import pyodbc    
import pandas as pd
from sqlalchemy import create_engine
        
        cnxn = create_engine('mssql+pyodbc://connection.info.here')
        
        sql_query = """
            QUERY
            """
        
        df = pd.read_sql_query(sql_query, cnxn)
        
        writer = pd.ExcelWriter('foo.xlsx')
        df.to_excel(writer, sheet_name='bar')
        writer.save()

When I run the script it looks like it's working - it takes a little bit, but then it returns this error in the stacktrace.

sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

I know the query works because I get the expected results in Microsoft SQL Management Studio in about 10 seconds.

So it turns out that since I'm using a hostname and not an IP address for the database in my connection string i have to specify the driver .

It would look like this.

cnxn = create_engine("mssql+pyodbc://user:password@hostname:port/databasename?driver=SQL+Server")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM