如何使用Python(Pandas)打开SQL Server .mdf文件 [英] How to open a SQL Server .mdf file with Python (pandas)

查看:1147
本文介绍了如何使用Python(Pandas)打开SQL Server .mdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开已保存到桌面的mdf sql数据库文件.如何将其作为熊猫数据框打开?到目前为止,我所拥有的只是以下内容:

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)

它给我错误信息

OperationalError :("08001","[08001] [Microsoft] [ODBC SQL Server驱动程序]既不提供DSN也不提供SERVER关键字(0)(SQLDriverConnect)")

OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')

我发现了另一个类似的问题,但是也没有得到回答.我也一直找不到很好的教程来开始将Python和sql数据库一起使用,这是我的新手.让我知道我是否可以提供其他信息.预先感谢.

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.

推荐答案

我的桌面上有一个mdf文件,无法用python打开该文件.

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

是的,您可以将其作为二进制文件打开,但随后需要编写代码来解释文件的内容.换句话说,您需要对SQL Server用于将数据库对象写入.mdf文件的逻辑进行逆向工程.

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 Express Edition,附加.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.

或者,您可以使用如下代码来代替将.mdf文件手动附加到SQL Server实例:

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)

这篇关于如何使用Python(Pandas)打开SQL Server .mdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆