Pyt*_*per 6 python dataframe python-3.x pandas pandas-to-sql
我正在使用 Pandas DataFrame.to_SQL() 将数据从数据帧插入到表中。如果单个记录存在加载问题,则不会加载任何内容,例如:如果整数列在一行中包含字符数据或日期格式在一条记录中无效等。
如何忽略这些错误?我想至少加载有效的数据,而不是在这种情况下根本不加载任何内容。
看来您正在寻找 Pythontry和exceptblock。
\n\n\nPython 将 try 语句后面的代码作为程序的 \xe2\x80\x9cnormal\xe2\x80\x9d 部分执行。except 语句后面的代码是program\xe2\x80\x99 对前面的try 子句中的任何异常的响应。(来源)
\n
对于您的特定用例,当您想要使用时pandas.DataFrame.to_sql,以下应该可以完成工作
def insert_data(df, table_name): # df is a dataframe, table_name is a string\n    try: # if there are errors, ignore them and load the valid data\n        df.to_sql(table_name, con=engine, if_exists=\'append\', index=False) # if_exists=\'append\' means that if the table already exists, it will append the new data to the existing table\n    except Exception as e:\n        print(e) # print the error\n        df.to_sql(table_name, con=engine, if_exists=\'append\', index=False, chunksize=1000) # chunksize=1000 means that the data will be loaded in chunks of 1000 rows\n