always_here

지식을 공유하고 함께 성장하는 엔지니어 as_always 입니다

AS_ALWAYS

핀테크 교육/금융데이터 활용

파이썬 - 데이터베이스 연결

nauung_always 2022. 7. 14. 20:54
728x90

데이터를 데이터베이스에 연결하여 저장하고 싶어 코드를 구현해보았습니다. 

  • pymysql 을 통해 데이터 베이스와 연결
    self.conn = pymysql.connect(host = , user = , password = , db = , charset = )

  • with self.conn.cursor() as curs
    sql="""
    CREATE TABLE IF NOT EXISTS news_raw ( )
    """
    curs.execute(sql)
  • self.conn.commit() 데이터베이스 저장
  • conn.close() 연결 해제

  • with self.conn.cursor() as curs:
    sql = f"REPLACE INTO news_raw VALUES ('{r.date}','{r.title}','{r.content}')"
    curs.execute(sql)
    self.conn.commit()
    DB에 저장 완료

 

728x90