Python Pandas to_sql, how to create a table with a primary key?

Simply add the primary key after uploading the table with pandas.

group_export.to_sql(con=engine, name=example_table, if_exists="replace", 
                    flavor="mysql", index=False)

with engine.connect() as con:
    con.execute('ALTER TABLE `example_table` ADD PRIMARY KEY (`ID_column`);')

Leave a Comment