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:
conn=pyodbc.connect(driver='{SQL Server}', dsn=filepath)
Its giving me the error message
OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')
I found another question that was similar but it was also unanswered. I have also been unable to find a good tutorial to start using sql databases with python I'm very new to the topic. Let me know if there is any extra information I can give. Thanks in advance.
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)
来源:https://stackoverflow.com/questions/53307559/how-to-open-a-sql-server-mdf-file-with-python-pandas