import io
import csv
def df2db(df_a, table_name, engine):
output = io.StringIO()
# ignore the index
# df_a.to_csv(output, sep='', index = False, header = False, quoting=csv.QUOTE_NONE)
df_a.to_csv(output, sep='', index = False, header = False, quoting=csv.QUOTE_NONE, escapechar='\')
output.getvalue()
# jump to start of stream
output.seek(0)
#engine <--- from sqlalchemy import create_engine
connection = engine.raw_connection()
cursor = connection.cursor()
# null value become ''
cursor.copy_from(output,table_name,null='')
connection.commit()
cursor.close()
use the function df2db
to insert a df
to an exists table, as the cols of the table and the df's columns should be the same.
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://user:psw@localhost:5432/dbname')
df2db(df, table_name, engine)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…