Hi, I’m trying to create a function that will take a table in insert(add) to the database.
My Code :
def save_database(table_name): table_name.head(0).to_sql('table_name', engine, if_exists='replace',index=False) conn = engine.raw_connection() cur = conn.cursor() output = io.StringIO() table_name.to_csv(output, sep='t', header=False, index=False) output.seek(0) contents = output.getvalue() cur.copy_from(output,'table_name', null="") conn.commit()
this is the old code when i didn’t create a function:
CustomerTable.head(0).to_sql('CustomerTable', engine, if_exists='replace',index=False) conn = engine.raw_connection() cur = conn.cursor() output = io.StringIO() CustomerTable.to_csv(output, sep='t', header=False, index=False) output.seek(0) contents = output.getvalue() cur.copy_from(output, 'CustomerTable', null="") conn.commit()
Advertisement
Answer
You seem to have put table_name
under quotations in your to_sql
function.
Also, you seem to be tackling the issue of data model creation and maintenance, which already has a lot of tooling in Python around it. Consider using something like alembic
Hope this helps.