pandas로 DB 불러오기 및 저장

파도·2022년 9월 7일
0

DB 불러오기 및 저장

(* cursor : 명령어를 db에 전달하여 정보를 가져오는 역할)

1.Database에서 pandas Dataframe으로 가져오는 방법

  • pd.read_sql("SELECT 구문",sqlite3연결,index_col='인덱스로 쓸 컬럼이름')

    ex) MSFT 파일을 가져오는 경우
    pd.read_sql("SELECT * FROM MSFT;",connection,index_col='Date')

  • 컬럼만 따로 불러오고 싶을 경우, SELECT 뒤에 컬럼명 작성

2. pandas Dataframe을 Database에 저장

  • df.to_sql(테이블명,sqlite3연결, if_exists='append or replace')

  • 테이블이 원래 있는 경우

    • f_exists{'fail','replace','append'}
      1️⃣ fail(디폴트 값): 테이블이 이미 존재하면 에러 발생
      2️⃣ replace: 기본의 테이블을 버리고 새로 넣음
      3️⃣ append: 기존의 테이블에 추가로 넣음

ex)

aapl.to_sql('AAPL',connection,if_exists='append'
msft.to_sql('MSFT',connection,if_exists='replace')
connection.commit()
connection.close()

@참고: https://seong6496.tistory.com/235

profile
우당탕탕 / 블로그 이사 중

0개의 댓글