简体   繁体   English

如何使用Python(Pandas)打开SQL Server .mdf文件

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

I'm trying to open a mdf sql database file that I have saved to my desktop. 我正在尝试打开已保存到桌面的mdf sql数据库文件。 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)') OperationalError :(“ 08001”,“ [08001] [Microsoft] [ODBC SQL Server驱动程序]既不提供DSN也不提供SERVER关键字(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. 我也一直找不到很好的教程来开始将Python和sql数据库一起使用。 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. 我的桌面上有一个mdf文件,无法用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. 换句话说,您将需要对SQL Server用于将数据库对象写入.mdf文件的逻辑进行逆向工程。

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. 仅安装SQL Server Express Edition,附加.mdf文件,然后照常访问数据库,可能会更容易。

Or, instead of manually attaching the .mdf file to the SQL Server instance you could use code like this: 或者,可以使用如下代码代替将.mdf文件手动附加到SQL Server实例:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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