从 SQL server 和 pyodbc 执行的查询导致不同的输出

问题描述 投票:0回答:0

我正在尝试编写一个代码,使用 pyodbc 将 SQL 查询执行到我的 SQL 服务器中。然后将从查询中选择的临时表导出到 csv 文件。但是,结果输出似乎与应有的不同。

在 SQL 服务器提示符下运行查询时,它返回 235 行表。 但是当它与 pyodbc 一起运行时,它返回 32.

代码是这样的:



# Set up a connection to your SQL Server
server =  server_name
database = db_name

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes;, timeout')

# Set up a cursor to execute SQL queries
cursor = cnxn.cursor()

# Define file paths
query_file = query_directory
output_file = output_directory

# Read the SQL query from the text file
with open(query_file, 'r') as f:
    queries = f.read()

# Execute the query

try: 
    cursor.execute(queries)
    print('\n' + ' SQL Queries Executed Sucessfully')
except pyodbc.Error as ex:
    print(f'\nError executing query: {queries}')
    print(f'\nError: {ex}')

# Fetch the results
results = cursor.fetchall()

# Get the column names
columns = [column[0] for column in cursor.description]

# Create a DataFrame from the results and column names
df = pd.DataFrame.from_records(results, columns=columns)

# Export the result to a CSV file
df.to_csv(output_file, index=False)

# Close the cursor and connection
cursor.close()
cnxn.close()

SQL代码在这里:https://github.com/kun-w-lee/random/blob/main/SQL
我相信问题出在 SQL 的 while 循环中,因为 #ProfileData_DomainsOnly 也会产生 32 行。

这里生成的 pyodbc 代码有什么问题,所以 SQL 函数没有被正确处理?

python sql-server pyodbc
© www.soinside.com 2019 - 2024. All rights reserved.