gpt4 book ai didi

python - 使用 Jupyter Notebook 将 SQL 转换为 Pandas Dataframe

转载 作者:行者123 更新时间:2023-12-01 09:10:00 25 4
gpt4 key购买 nike

我正在尝试使用 Jupyter Notebook 获取对 Pandas 数据框的 SQL 查询。

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

最佳答案

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

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. 此特定问题不是由您的网络限制引起的。

关于python - 使用 Jupyter Notebook 将 SQL 转换为 Pandas Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51739196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com