SQLSERVER-> Python(Analytics)df-> POSTGRESSQL INSERT(每小时一次计划)
Postgres
1.实际表-'GEMS'
2.临时表-'Temp'
我使用python查询SQL Server,在完成数据准备后,需要将数据插入PostgreSQL。
我创建了一个临时表,以避免在通过python查询插入PostgreSQL实际表期间出现任何重复错误。
我是PostgreSQL和SQL的新手。想知道是否有更好的方法
import io
import pyodbc
import psycopg2
import pandas as pd
from sqlalchemy import create_engine
sql_conn = pyodbc.connect('DRIVER={SQL Server};SERVER=IOT-BODY1-PROD\IOT_STAGE;PORT=1433;UID=***;PWD=****;')
engine = create_engine('postgresql+psycopg2://postgres:postgres@IOT:5432/Energy')
conn = engine.raw_connection()
cur = conn.cursor()
df.head(0).to_sql('GEMS', engine, if_exists='append',index=False) #-Actual Table
df.head(0).to_sql('temp', engine, if_exists='append',index=False) #Temp Table
#cols=['DATETIME','SHOP','KWH','HOUR','DATE','TIME','ZCDAY','UID','SHIFT','WERKS']
if len(df) > 0:
df_columns = list(df)
# create (col1,col2,...)
columns = ",".join(df_columns)
for i in columns:
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'temp',null="")
cur.execute("""Insert into public."""+'"{}"'.format(i)+""" select * From public.temp ON CONFLICT DO NOTHING;""");
cur.execute("""Delete FROM public.temp;""");
conn.commit()
错误:
---> 13 cur.copy_from(output, 'temp',null="")
14 cur.execute("""Insert into public."""+'"{}"'.format(i)+""" select * From public.temp ON CONFLICT DO NOTHING;""");
15 cur.execute("""Delete FROM public.temp;""");
InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block
如何解决此错误?