0

I am struggling with an minor issue that I am trying to create a table into MySQL using Python sqlalchemy, which crates table into the database not did not inserting rows into that. Below is the code. what is the mistake?

import pandas as pd
from sqlalchemy import create_engine

engine = create_engine("mysql://root:1234@localhost:3306/paintings")
connection = engine.connect()

df = pd.read_csv("./data/artist.csv")
df.to_sql("artist", con=connection, index=False, if_exists="replace")

enter image description here

5
  • 1
    does the dataframe gave any data? Commented Jan 10, 2024 at 20:36
  • can you try connection.commit() after df.to_sql("artist", con=connection, index=False, if_exists="replace")? Commented Jan 11, 2024 at 2:49
  • @nbk, yes df returns me the data. Commented Jan 11, 2024 at 17:35
  • 1
    @python_user, brother you are amazing, your suggestion works. But beyond to my curiosity I want to know what does this commit function? Commented Jan 11, 2024 at 17:40
  • Commit allows you to persist the changes you made (e.g., adding new rows, deleting or modifying existing ones) to the database. This allows you to make changes locally and submit them when you are done. In your code, you create a connection to the db and add new rows to the table. But you have not committed them yet. Commented Jan 16, 2024 at 16:10

1 Answer 1

0

You are trying to push changes to the database, specifically, add new rows to 'artist' table from a csv. In your code, you properly read the csv and create a connection to the database and prepare your database changes, but forgot to persist them. You can do this by calling the commit on the connection. So, it would be

import pandas as pd
from sqlalchemy import create_engine

engine = create_engine("mysql://root:1234@localhost:3306/paintings")
df = pd.read_csv("./data/artist.csv")

with engine.connect() as connection:
    df.to_sql("artist", con=connection, index=False, if_exists="replace")
    connection.commit()

The last statement would persist your prepared changes to the database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.