【问题标题】:Using Jupyter notebook to convert SQL into Panda Data Frame使用 Jupyter notebook 将 SQL 转换为 Panda Dataframe
【发布时间】:2019-01-15 06:38:27
【问题描述】:

我正在尝试使用 Jupyter Notebook 将 SQL 查询提取到 Pandas 数据框。

我关注了these instruction from 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 发行版。

【问题讨论】:

  • 第二行代码变量sql没有定义!

标签: python sql sql-server pandas jupyter-notebook


【解决方案1】:

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

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()
  • 您在第 2 行调用变量 sql,但实际上直到第 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 更改为数据库中的信息。有一个很好的例子说明你需要在那里输入文字here
  2. 此特定问题不是由您的网络限制引起的。

【讨论】:

  • 感谢您的回答。下次我会注意我的代码顺序。
  • 例如,如果我的数据库是 AdventureWorks2012,那么我应该将我的 connection_info 更改为什么?
  • 请访问并阅读我在第 2 点的回答中包含的链接
猜你喜欢
  • 2017-09-08
  • 2018-04-25
  • 2019-11-23
  • 2016-06-01
  • 2019-05-17
  • 2019-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多