pandas 表在 mysql 数据库中插入 0 行?

问题描述 投票:0回答:1

当我尝试将数据放入 MySQL 数据库时,它仅放入结构数据,并且没有任何行插入 MySQL 数据库中。可能是什么问题?

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')

我尝试添加 method=None,添加 dframe 但没有任何效果。

python pandas dataframe mysql-python
1个回答
0
投票

我没有看到提交。

 # Add the following line to commit changes
db_connection.commit()

# Close the connection when done
db_connection.close()
© www.soinside.com 2019 - 2024. All rights reserved.