【发布时间】:2021-06-16 03:29:40
【问题描述】:
我是 SQL 查询的新手。我正在用 python 编写代码和查询数据库。下面是我的代码,我不确定代码的问题:
import pyodbc
import pandas as pd
import numpy as np
#import datetime
from pandas import ExcelWriter
from pandas import ExcelFile
df_lots=pd.DataFrame()
sql = """
DECLARE @carts NVARCHAR(25) = 'Large';
DECLARE @item_type NVARCHAR(50)= 'Produce';
DECLARE @read_point INT= 0;
DECLARE @item_type NVARCHAR(MAX)= N'';
SELECT @item_type+=N',' + [items]
FROM
(
SELECT distinct D.items
FROM [dbo].[ITEM_SET_COMPACT_VIEW] D
JOIN [dbo].[Placement] E
ON D.items=E.items
WHERE D.[items] LIKE 'Large'
) x
ORDER BY items;
SET @item_type = STUFF(@item_type, 1, 1, '');
SELECT *
FROM [dbo].[Get_Data](@item_type, @item_type, @read_point, 1, 0);
"""
try:
mssql_connection = pyodbc.connect('''
DRIVER=ODBC Driver 17 for SQL Server;
SERVER=XXXXXXX;
DATABASE=XXXXXX;
UID=XXXXXXXX;
PWD=XXXXXXXX;
''')
with mssql_connection.cursor() as cursor:
cursor.execute(sql )
lots=cursor.fetchall()
except pyodbc.Error as ex:
print(f"Unexpected error {ex}")
df_lots=pd.DataFrame(np.array(lots))
当我运行上面的代码时,它给了我以下错误:
意外错误没有结果。以前的 SQL 不是查询。
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-e3e7b4c5dae4> in <module>
45 except pyodbc.Error as ex:
46 print(f"Unexpected error {ex}")
---> 47 df_lots=pd.DataFrame(np.array(lots))
NameError: name 'lots' is not defined
谁能帮我解决这个问题??
【问题讨论】:
-
代码中有一处修改:
DECLARE @items NVARCHAR(50)= 'Produce';FROM [dbo].[Get_Data](@items, @item_type, @read_point, 1, 0);
标签: python sql pandas odbc pyodbc