to_sql向不存在的表时候,默认创建一个新表,这时新表的列类型可能并不是你期望的。
可以在执行 to_sql 方法时,将映射好列名和指定类型的 dict 赋值给 dtype 参数即可上,其中对于 MySQL 表的列类型可以使用 SQLAlchemy 包中封装好的类型
from sqlalchemy.types import NVARCHAR, Float, Integer
dtypedict = {
'str': NVARCHAR(length=255),
'int': Integer(),
'float' Float()
}
df.to_sql(name='test', con=con, if_exists='append', index=False, dtype=dtypedict)
也可以创建映射函数:
def mapping_df_types(df):
dtypedict = {}
for i, j in zip(df.columns, df.dtypes):
if "object" in str(j):
dtypedict.update({i: NVARCHAR(length=255)})
if "float" in str(j):
dtypedict.update({i: Float(precision=2, asdecimal=True)})
if "int" in str(j):
dtypedict.update({i: Integer()})
return dtypedict
df = pd.DataFrame([['a', 1, 1, 2.0, datetime.now(), True]],
columns=['str', 'int', 'float', 'datetime', 'boolean'])
dtypedict = mapping_df_types(df)
df.to_sql(name='test', con=con, if_exists='append', index=False, dtype=dtypedict)