python把dataframe回写到mysql和pg库

def pyWriteToMysql(data_df , db_param , table_name ):
    try:
        connect_url = 'mysql+pymysql://' + db_param.get('username') + ':' + db_param.get('password') + '@' +  db_param.get('host') + ':' + str(db_param.get('port') )+ '/' + db_param.get('database')
        from sqlalchemy import create_engine
        engine = create_engine(connect_url, encoding='utf8')
        data_df.to_sql(table_name,engine,index = False ,if_exists = 'append')  ## 参数按需设置
        print('回写成功')   
    except Exception as e:
        print(e) 

## 把python 中的数据回写到pg数据库中    
## data_df 需要回写的数据
## db_param 数据库的参数
## table_name 回写的表名
## 把data_df回写到table_name表中
def pyWriteToPg(data_df , db_param , table_name ):
    try:
        connect_url = 'postgresql://' + db_param.get('username') + ':' + db_param.get('password') + '@' +  db_param.get('host') + ':' + str(db_param.get('port') )+ '/' + db_param.get('database')
        from sqlalchemy import create_engine
        engine = create_engine(connect_url, encoding='utf8')
        data_df.to_sql(table_name,engine,index = False ,if_exists = 'append')  ## 参数按需设置
        print('回写成功')   
    except Exception as e:
        print(e)   
# 调用示例
import pandas as pd
if __name__ == '__main__':
# mysql的环境配置
    pg_params =   {'host' : IP地址,
                      'username': 用户名,
                      'password': 密码,
                      'port': 端口,
                      'database' : schema
        			   }
pyWriteToMysql(数据框名称, mysql_params , 表名 )     
pyWriteToPg(数据框名称, db_param , 表名)

你可能感兴趣的:(python,数据库)