Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading