AttributeError when using pandas to_sql

Question:

I am trying to upload a dataframe to my sqlalchemy model/sqlite database. I have this dataframe

dataset = {'id': [1], 'creationDate':['2022-10-15'], 'value':['5']}
df=pd.DataFrame(data=dataset)
df.to_sql('Apple_health_export', engine, if_exists='append', index=False)

The data does upload to the database but I keep getting this error:

AttributeError: 'function' object has no attribute 'currentframe'

I don’t understand it. Is anyone familiar with what this is or know how I can fix it?

update with github repo

Models.py

from sqlalchemy import create_engine, inspect
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session, relationship
from sqlalchemy import Column, Integer, Text

SQL_URI = r"sqlite:///D:databaseszTestModelsmodels02.db"

Base = declarative_base()
engine = create_engine(SQL_URI, echo = False)
Session = sessionmaker(bind = engine)
sess = Session()

class Apple_health_export(Base):
    __tablename__ = 'apple_health_export'
    id = Column(Integer,primary_key = True)
    creationDate = Column(Text)
    value = Column(Text)

    def __repr__(self):
        return f'Apple_health_export(id: {self.id},'  
            f'creationDate: {self.creationDate})'

#Build db
if 'users' in inspect(engine).get_table_names():
    print('db already exists')
else:
    Base.metadata.create_all(engine)
    print('NEW db created.')

Error traceback

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In [3], line 1
----> 1 df.to_sql('Apple_health_export', engine, if_exists='append', index=False)

File ~Documents_environmentsws08weblibsite-packagespandascoregeneric.py:2986, in NDFrame.to_sql(self, name, con, schema, if_exists, index, index_label, chunksize, dtype, method)
   2829 """
   2830 Write records stored in a DataFrame to a SQL database.
   2831 
   (...)
   2982 [(1,), (None,), (2,)]
   2983 """  # noqa:E501
   2984 from pandas.io import sql
-> 2986 return sql.to_sql(
   2987     self,
   2988     name,
   2989     con,
   2990     schema=schema,
   2991     if_exists=if_exists,
   2992     index=index,
   2993     index_label=index_label,
   2994     chunksize=chunksize,
   2995     dtype=dtype,
   2996     method=method,
   2997 )

File ~Documents_environmentsws08weblibsite-packagespandasiosql.py:696, in to_sql(frame, name, con, schema, if_exists, index, index_label, chunksize, dtype, method, engine, **engine_kwargs)
    691 elif not isinstance(frame, DataFrame):
    692     raise NotImplementedError(
    693         "'frame' argument should be either a Series or a DataFrame"
    694     )
--> 696 return pandas_sql.to_sql(
    697     frame,
    698     name,
    699     if_exists=if_exists,
    700     index=index,
    701     index_label=index_label,
    702     schema=schema,
    703     chunksize=chunksize,
    704     dtype=dtype,
    705     method=method,
    706     engine=engine,
    707     **engine_kwargs,
    708 )

File ~Documents_environmentsws08weblibsite-packagespandasiosql.py:1751, in SQLDatabase.to_sql(self, frame, name, if_exists, index, index_label, schema, chunksize, dtype, method, engine, **engine_kwargs)
   1729 table = self.prep_table(
   1730     frame=frame,
   1731     name=name,
   (...)
   1736     dtype=dtype,
   1737 )
   1739 total_inserted = sql_engine.insert_records(
   1740     table=table,
   1741     con=self.connectable,
   (...)
   1748     **engine_kwargs,
   1749 )
-> 1751 self.check_case_sensitive(name=name, schema=schema)
   1752 return total_inserted

File ~Documents_environmentsws08weblibsite-packagespandasiosql.py:1662, in SQLDatabase.check_case_sensitive(self, name, schema)
   1652 if name not in table_names:
   1653     msg = (
   1654         f"The provided table name '{name}' is not found exactly as "
   1655         "such in the database after writing the table, possibly "
   1656         "due to case sensitivity issues. Consider using lower "
   1657         "case table names."
   1658     )
   1659     warnings.warn(
   1660         msg,
   1661         UserWarning,
-> 1662         stacklevel=find_stack_level(inspect.currentframe()),
   1663     )

AttributeError: 'function' object has no attribute 'currentframe'
Asked By: costa rica

||

Answers:

As the error traceback suggests, there’s no table in the database with the given name:

The provided table name ‘{name}’ is not found exactly as such in the database

It seems that this is due to a case sensitivity issue. In the table model:

class Apple_health_export(Base):
    __tablename__ = 'apple_health_export'

In the initial code snippet:

df.to_sql('Apple_health_export', engine, if_exists='append', index=False)

apple_health_export’ is not equal to ‘Apple_health_export’.

Answered By: msamsami
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.