pandas to_sql报错处理

def save_to_sql(joint_table,table_name,ip,user,database,password):
    con=pymysql.connect(host=ip, user=user, password=password,
                          database=database, port=3306,     unix_socket=None,
                          charset='UTF8')
    joint_table.to_sql(table_name,con,if_exists='replace')

报错:Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting
经过网上搜索类似错误发现pymysql可以从mysql数据库中导出数据,但是导入到mysql时却会出现上述报错。解决方法是使用sqlalchemy 库的create_engine
示例如下:

import pandas as pd
import numpy as np
import pymysql
from sqlalchemy import create_engine

def save_to_sql(joint_table,table_name,ip,user,database,password):
    con = create_engine("mysql+pymysql://{}:{}@{}:3306/{}?charset=gbk".format(user,password,ip,database))
    joint_table.to_sql(table_name,con,if_exists='replace')

df=pd.DataFrame(np.random.randn(3,6))

if __name__=='__main__':
    save_to_sql(df,'odf','106.xx.xxx','root','order',"******")
 

这样便不会报错了!

你可能感兴趣的:(pandas to_sql报错处理)