python - 使用 Jupyter notebook 将 SQL 转换为 Panda Data Frame
问题描述
我正在尝试使用 Jupyter Notebook 将 SQL 查询获取到 Pandas 数据框。
我遵循了 Beardc 的这些指示:
import pandas as pd
df = pd.read_sql(sql, cnxn)
cnxn = pyodbc.connect(connection_info)
cursor = cnxn.cursor()
sql = """SELECT * FROM AdventureWorks2012.Person.Address
WHERE City = 'Bothell'
ORDER BY AddressID ASC"""
df = psql.frame_query(sql, cnxn)
cnxn.close()
但是,每当我运行代码时,它都会显示:
NameError
Traceback (most recent call last)
<ipython-input-5-4ea4efb152fe> in <module>()
1 import pandas as pd
2
3 df = pd.read_sql(sql, cnxn)
4
5 cnxn = pyodbc.connect(connection_info)
NameError: name 'sql' is not defined
我正在使用受监控的网络(如果有人要求,公司网络)。
我有几个问题想问:
- 我是否必须将其更改
connection_info
为我的数据库中的信息? - 我连接到可能对端口连接有限制的网络是否重要?随着公司建立其中的一些。
我正在使用最新的 Anaconda 发行版。
解决方案
您收到的错误是由您的代码顺序引起的:
1 import pandas as pd
2 df = pd.read_sql(sql, cnxn) ## You call the variable sql here, but don't assign it until line 6
3
4 cnxn = pyodbc.connect(connection_info)
5 cursor = cnxn.cursor()
6 sql = """SELECT * FROM AdventureWorks2012.Person.Address
7 WHERE City = 'Bothell'
8 ORDER BY AddressID ASC"""
9 df = psql.frame_query(sql, cnxn)
10 cnxn.close()
- 您
sql
在第 2 行调用变量,但直到第 6 行才真正定义变量。 - 您还缺少一些库,并且根据 Beardc 的代码,您似乎已经将他的两个答案的一些错误部分融合在一起。
尝试像这样安排代码:
(请注意此代码未经测试,其他问题如下所述)
#Import the libraries
import pandas as pd
import pyodbc
#Give the connection info
cnxn = pyodbc.connect(connection_info)
#Assign the SQL query to a variable
sql = "SELECT * FROM AdventureWorks2012.Person.Address WHERE City = 'Bothell' ORDER BY AddressID ASC"
#Read the SQL to a Pandas dataframe
df = pd.read_sql(sql, cnxn)
在回答您的问题时:
- 是的,您需要将 connection_info 更改为数据库中的信息。有一个很好的例子说明您需要在此处输入文本
- 此特定问题不是由您的网络限制引起的。
推荐阅读
- c# - GroupBy 项不相等
- java - 使用流图java 8转换另一个列表
- ios - 流式传输视频通话时无法设置正确的视图
- firebase - 如何删除创建的firestore数据库。?
- reactjs - 如何在 FlatList 中的每个项目上实现 Counter
- apache - Apache 不会释放工作线程 (mpm-event)
- powershell - AzureDevops PowerShell 和任务
- javascript - 识别输入文本中的表情符号
- .htaccess - htaccess RewriteRule 导致“找不到对象!”
- macos - 使用 Applescript 从 OSX 日历中删除事件