【发布时间】:2020-11-11 02:41:36
【问题描述】:
我正在尝试从包含多个工作表的 Excel 文件中插入数据,每个工作表名称都存在于数据库中的相应表中。现在我认为的一种方法是在工作表名称上循环并在循环中创建一个递归 SQL,该循环适用于所有工作表名称。现在在循环中假设第一个工作表名称出现然后几乎没有检查数据库中是否存在表并验证工作表中的列名以及数据库中的列名。如果一切正常,它会将工作表数据插入数据库。
我面临的挑战是:
1 - 从 pandas 获取 Sheetname
xls = pd.ExcelFile<filepath>
Sheet_name = x.sheet_names
I am not able to loop through it although it contains all the sheet name but for() is not working.
Help me with a iteration code.
2 - 帮我从每张纸的头行切出列名以确认列名。
I am placing a few piece of code that i have been working on, help me with syntax error's as well
Their are errors in SQL code as well Please help me with them also
代码:
import pandas as pd
Import the oracle lib
Create -----> DB_Connection
mycursor = DB_Connection.cursor()
xls = pd.ExcelFile('File Path')
SheetNames = xls.sheet_names
for i in SheetNames:
SelectSql = "SELECT TABLE_NAME FROM all_tab_columns where OWNER = 'XYZZZ' and TABLE_NAME = '"i"' "
mycursor.execute(SelectSql)
QueryResult = mycursor.fethcone()
if(pd.isnull(QueryResult)):
Print("Table doesn't exist in database")
else:
""" Add the Data frame slicing code to get Column name's to Check if same Exist in Database or Not """
GetColumnSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"i"' ORDER BY ORDINAL_POSITION"
mycursor.execute(GetColumnSql)
ColumnName = mycursor.fetchall()
InsertSql = "INSERT INTO '"i"'('"ColumnName"') VALUES(%s,%s,%s,%s,%s)"
VAL0 = """ insert from dataframe """
mycursor.execute(InsertSql,VAL0)
DB_Connection.commit();
【问题讨论】: