首页 > 解决方案 > 使用 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

我正在使用受监控的网络(如果有人要求,公司网络)。

我有几个问题想问:

  1. 我是否必须将其更改connection_info为我的数据库中的信息?
  2. 我连接到可能对端口连接有限制的网络是否重要?随着公司建立其中的一些。

我正在使用最新的 Anaconda 发行版。

标签: pythonsqlsql-serverpandasjupyter-notebook

解决方案


您收到的错误是由您的代码顺序引起的:

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)

在回答您的问题时:

  1. 是的,您需要将 connection_info 更改为数据库中的信息。有一个很好的例子说明您需要在此处输入文本
  2. 此特定问题不是由您的网络限制引起的。

推荐阅读