How to open a SQL Server .mdf file with Python (pandas)

泄露秘密 提交于 2019-12-02 06:35:07

I have a mdf file on my desktop is there no way to just open that file in python.

Well, yes, you could open it as a binary file but then you'd need to write the code to interpret the contents of the file. In other words, you would need to reverse-engineer the logic that SQL Server uses to write database objects to the .mdf file.

It would probably be easier for you to just install SQL Server Express Edition, attach the .mdf file, and then access the database as usual.

Or, instead of manually attaching the .mdf file to the SQL Server instance you could use code like this:

import pandas as pd
import pyodbc

cnxn_str = (
    r'DRIVER=ODBC Driver 11 for SQL Server;'
    r'SERVER=(local)\SQLEXPRESS;'
    r'Trusted_Connection=yes;'
    r'AttachDbFileName=C:\Users\Gord\Desktop\zzz.mdf;'
)
cnxn = pyodbc.connect(cnxn_str)
df = pd.read_sql("SELECT * FROM Table1", cnxn)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!