pandas to_sql 1406 Data too long for column
(pymysql.err.DataError) (1406, "Data too long for column 'favIconUrl' at row 1")
解决办法
df = pd.DataFrame([['a', 1, 1, 2.0, datetime.now(), True]], columns=['str', 'int', 'float', 'datetime', 'boolean'])
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
dtypedict = mapping_df_types(df) df.to_sql(name='test', con=con, if_exists='append', index=False, dtype=dtypedict)
pandas.DataFrame.to_sql
- DataFrame.to_sql(name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)
- dtype 可以指定类型;
- 参考
- [pandas.DataFrame.to_sql — pandas 1.4.0 documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html )]
- [在pandas.DataFrame.to_sql时指定数据库表的列类型 - SegmentFault 思否](https://segmentfault.com/a/1190000012968488 )]