9rep --Pandas MySQL

Data SELECT INSERT using Pandas (additional)

--Get to MySQL via Pandas --Insert CSV to MySQL with Pandas

import pandas as pd
from sqlalchemy import create_engine
import sqlalchemy as sa
import sys
import datetime

class MySqlPandas():

    def __init__(self):
    		self.engine = create_engine('mysql+pymysql://{USER}:{PASSWORD}@{HOST}:{PORT}/{DB NAME}')

    def sesStoreData(self):
        sql = '''
				SELECT
				    tb.hoge1                       
				,   tb.hoge2                     
				,   tb.hoge3               
				FROM
				    table tb
				;
				'''

        df = pd.read_sql_query(sql, self.engine)

        df.to_csv('ses_table_' + str(datetime.date.today()) + '.tsv', sep='\t')

    def insStoreData(self):
        df_ins = pd.read_csv('all_table.tsv', delimiter='\t')

        df_ins_new = df_ins.rename(columns={'hoge1': 'col1', 'hoge2': 'col2', 'hoge3': 'col3'})

        df_ins_new.to_sql('store_master', self.engine, index=False, if_exists='append') #Full replacement is if_exists='replace'


if __name__ == '__main__':
    myp = MySqlPandas()
    # myp.sesStoreData()select execution
    myp.insStoreData()Insert execution
 

Recommended Posts

9rep --Pandas MySQL
Pandas
8rep --Pandas string delete code
Pandas memo
Pandas basics
Pandas notes
Pandas memorandum
Pandas basics
pandas memorandum
pandas memo
pandas SettingWithCopyWarning