바뀜

89번째 줄: 89번째 줄:  
|함수제작
 
|함수제작
 
|함수로 만들어 처리하면 편할 듯하다.
 
|함수로 만들어 처리하면 편할 듯하다.
 +
DB 객체와 테이블명을 넣어 작동한다.
 
|<syntaxhighlight lang="python">
 
|<syntaxhighlight lang="python">
def df_to_db(df, db):
+
def df_to_db(df, db, table):
      
+
     '''df를 받아 db에 저장하는 것.'''
 +
    cur = db.cursor()  # 커서를 만든다.
 +
    cols = "`,`".join([str(i) for i in df.columns.tolist()])  # df의 칼럼을 추출한다.
 +
    for i, row in df.iterrows():  # 하나씩 입력한다.
 +
        try:
 +
            sql = "INSERT INTO `{table}` (`{cols}`) VALUES (".format(table=table, cols=cols) +  "%s," * (
 +
                        len(row) - 1) + "%s)"  # 마지막엔 쉼표 없이.
 +
            cur.execute(sql, tuple(row))
 +
            # the connection is not autocommitted by default, so we must commit to save our changes
 +
            db.commit()
 +
        except Exception as e:
 +
            # print(e)
 +
            pass
 
</syntaxhighlight>
 
</syntaxhighlight>
 
|}
 
|}
 
[[분류:Pandas:DataFrame]]
 
[[분류:Pandas:DataFrame]]