Pandas to_sql to sqlite returns 'Engine' object has no attribute 'cursor'

adding in a raw_connection() worked for me

from sqlalchemy import create_engine

sql_engine = create_engine('sqlite:///test.db', echo=False)
connection = sql_engine.raw_connection()
working_df.to_sql('data', connection, index=False, if_exists='append')

I had conda install sqlalchemy during my notebook session, so while it was accessible, since I already initiated pandas, it appeared as if there was no sqlalchemy. Restarting the session allowed me to remove the raw_connection().

from sqlalchemy import create_engine

sql_engine = create_engine('sqlite:///test.db', echo=False)
connection = sql_engine
working_df.to_sql('data', connection, index=False, if_exists='append')

from sqlalchemy import create_engine
sql_engine = create_engine('sqlite:///test.db', echo=False)
working_df.to_sql('data', sql_engine,index=False, if_exists='append')

Instead of above code, can you try to use connect method of the engine object instead of engine object itself as below.,

sql_engine = create_engine('sqlite:///test.db', echo=False)
conn = sql_engine.connect()
working_df.to_sql('data', conn,index=False, if_exists='append')

Try above steps and let me know if you still facing the issue.


The following code was giving me the same error while I was working to push data to MS Sql Server:

engine_string = 'mssql+pyodbc://'+username_dsdb+':'+password_dsdb+'@'+server_dsdb+':1433/'+database_dsdb+'?driver=ODBC Driver 13 for SQL Server'
engine = sqlalchemy.create_engine(engine_string,deprecate_large_types=True)

conn_dsdb = engine.connect()

df_year_week_contract_wise.to_sql("KPIEngine_FACT_Historical", conn_dsdb, index=False, if_exists='append')

conn_dsdb.close()

But, then I restarted the session and it worked fine.