Search code examples
pythonpandasdataframemysql-python

The pandas table is inserting 0 rows in mysql database?


When I try to put data in MySQL database it only puts in the structure data, and there are no rows inserted into the MySQL database. What could be the issue?

import pandas as pd
from sqlalchemy import create_engine
import numpy as np

class Database:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None

    def get_db(self):
        try:
            if not self.connection:
                self.connection = create_engine(f'mysql+mysqlconnector://{self.user}:{self.password}@{self.host}/{self.database}')
                print("Connected to the database.")

            return self.connection.connect()
        except Exception as e:
            print(f"Error: {e}")

db_instance = Database(host='localhost', user='root', password='', database='test2')
db_connection = db_instance.get_db()

np.random.seed(0)
number_of_samples = 10
frame = pd.DataFrame({
    'feature1': np.random.random(number_of_samples),
    'feature2': np.random.random(number_of_samples),
    'class':    np.random.binomial(2, 0.1, size=number_of_samples),
    },columns=['feature1','feature2','class'])

frame.to_sql('ds_attribution_probabilities', con=db_connection, 
             index=False, if_exists='append')

I tried adding method=None, adding dframe but nothing worked at all.


Solution

  • I don’t see a commit.

     # Add the following line to commit changes
    db_connection.commit()
    
    # Close the connection when done
    db_connection.close()