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

前端 未结 1 1102
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 09:53

I\'m trying to open a mdf sql database file that I have saved to my desktop. How do you open it as a pandas dataframe? so far all I have is the following:

co         


        
相关标签:
1条回答
  • 2020-12-11 10:17

    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)
    
    0 讨论(0)
提交回复
热议问题