我试图在Python中编写一个函数,该函数将SQL查询发送到数据库,将检索到的数据存储在Python Dataframe中,并在命名选项卡上输出到Excel以进行大量查询。当"快捷方式的名称时,我得到它的工作#34;以前是手动运行但我不能写新的"快捷方式"函数调用的每个实例中的名称。
有人可以帮我调试这个问题吗?
这是Python代码:
import cx_Oracle
import pandas as pd
import xlwt as xls_write
writer = pd.ExcelWriter('<Excel File>')
def executeSQL(shortcut, tab, SQL):
conn = cx_Oracle.connect('<Connection String')
cursor= conn.cursor()
cursor.execute (SQL)
shortcut = pd.DataFrame(cursor.fetchall())
shortcut.columns = [rec[0] for rec in cursor.description]
cursor.close()
conn.close()
shortcut.to_excel(writer, tab, index=False)
executeSQL(tab1, 'Tab 1', "<SQL Statement>")
executeSQL(tab2, 'Tab 2', "<SQL Statement>")
executeSQL(tab3, 'Tab 3', "<SQL Statement>")
executeSQL(tab4, 'Tab 4', "<SQL Statement>")
executeSQL(tab5, 'Tab 5', "<SQL Statement>")
答案 0 :(得分:0)
为什么要传递快捷参数,然后在函数中再次定义它?我通常使用pyodbc进行连接,因为我没有你的实际数据,这里有一个模拟我将如何做到这一点:
import cx_Oracle
import pandas as pd
import xlwt as xls_write
writer = pd.ExcelWriter('<Excel File>')
conn = cx_Oracle.connect('<Connection String')
def executeSQL(tab, SQL, connection):
df = pd.read_sql(SQL,connection)
df.to_excel(writer, tab, index=False)
executeSQL('Tab 1', "<SQL Statement>")
executeSQL('Tab 2', "<SQL Statement>")
executeSQL('Tab 3', "<SQL Statement>")
executeSQL('Tab 4', "<SQL Statement>")
executeSQL('Tab 5', "<SQL Statement>")
conn.close()