我的python代码基于:
整个python代码已成功执行,但是生成了一个空白的csv文件,但没有从查询4的游标中得到任何输出。
我的示例代码:
import pyodbc
import pandas as pd
import csv
cnxn_1 = pyodbc.connect()
with open("""csv path""") as csv1:
reader = csv.reader(csv)
cursor_1 = cnxn_1.cursor()
cursor_1.execute("""INSERT INTO TABLE1""")
cursor_1.commit()
cnxn_1.close()
cnxn_2 = pyodbc.connect()
cursor_2 = cnxn_2.cursor()
cursor_2.execute("""exec stored_proc_select_statement @parameter""")
result_1 = cursor_2.fetchall()
print (result_1)
cnxn_2.close()
cnxn_3 = pyodbc.connect()
cursor_3 = cnxn_3.cursor()
cursor_3.execute("""exec stored_proc_update_statement @parameter""")
cursor_3.commit()
cnxn_3.close()
cnxn_4 = pyodbc.connect()
cursor_4 = cnxn_4.cursor()
cursor_4.execute("""exec stored_proc_final_select_statement @parameter""")
cursor_4.commit()
cnxn_4.close()
result_2 = cursor_4.fetchall()
print (result_1)
columns = [column[0] for column in cursor_4.description]
df = pd.DataFrame.from_records(result_2, columns=columns)
print(df)
df.to_csv("""new csv path""")
cnxn_4.close()
答案 0 :(得分:1)
您过早关闭了Connection 4:
cnxn_4 = pyodbc.connect()
cursor_4 = cnxn_4.cursor()
cursor_4.execute("""exec stored_proc_final_select_statement @parameter""")
cursor_4.commit()
# **cnxn_4.close()** ## Comment this out, or remove it.
result_2 = cursor_4.fetchall()
print (result_1)
columns = [column[0] for column in cursor_4.description]
df = pd.DataFrame.from_records(result_2, columns=columns)
print(df)
df.to_csv("""new csv path""")
cnxn_4.close()