Python/오류해결

[Python] sqlalchemy Attributeerror: 'engine' object has no attribute 'cursor' 에러 해결하기

공부하는 sum 2024. 1. 25. 15:38
728x90
engine_dm_db = sa.create_engine(AccessConfig().get_dm_db_connection_string())
df_unique_device = pd.read_sql(query, engine_dm_db)

 

이 코드를 작성해서 mssql에 있는 데이터를 가져오려고 했다. 

sqlalchemy를 이용해서 연결을 했는데,

 

 

실제 실행하려고 하니 Attributeerror: 'engine' object has no attribute 'cursor'  라는 오류가 난다

 

시도해 본 방법들

  • create_engine한 다음에 그 객체에 .connect()추가
    • 이 경우에는 connect에 cursor가 없다는 AttributeError: 'Connection' object has no attribute 'cursor' 에러로 바뀌었음
  • 껐다가 켜보기
    • 의외로 stackoverflow에서 이 방법을 해보라는 댓글이 많아서 해보았으나 실패

 

결국 해결을 본 방법은

engine_dm_db = sa.create_engine(AccessConfig().get_dm_db_connection_string())
engine_dm_db = engine_dm_db.raw_connection()
df_unique_device = pd.read_sql(query, engine_dm_db)

 

이렇게 raw_connection()을 해주는 방법이었다.

 

raw_connection을 호출하면, Connection 객체가 아니라 DBAPI의 연결 객체가 반환되어서 데이터베이스와의 직접적인 상호 작용을 수행할 수 있다고 한다.

 


참고

https://stackoverflow.com/questions/38332787/pandas-to-sql-to-sqlite-returns-engine-object-has-no-attribute-cursor

https://docs.sqlalchemy.org/en/13/core/connections.html#working-with-raw-dbapi-connections

728x90