【发布时间】:2021-01-03 02:36:39
【问题描述】:
我正在编写一个 spark 代码以从数据帧插入到 mysql 表中,但出现错误
df_to_write.write.format("jdbc").option("url", jdbc_url).option("driver", "com.mysql.jdbc.Driver")\
.option("dbtable", tbl_name).option("user", DBUser).option("password", DBPassword)\
.option("numPartitions",32).mode('append').save()
org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 18.0 failed 4 times, most recent failure: Lost task 1.3 in stage 18.0 (TID 170, 10.151.244.77, executor 0): java.sql.BatchUpdateException: Data truncation: Incorrect datetime value: '1970-01-01 00:00:00' for column
这是我发现的,因为列的值为 1970-01-01 00:00:00
但是,如果我在 mysql 工作台中运行插入语句,它会发出警告,并且值被插入为 0000
示例如下:
create table test_time (processing_ts timestamp NULL DEFAULT NULL);
insert into test_time values ('1990-01-01T00:00:00.000+0000'),('1990-01-01T00:00:00.000+0000'),('1970-01-01T00:00:00.000+0000');
表格输出的值如下
1990-01-01 00:00:00
1990-01-01 00:00:00
0000-00-00 00:00:00 --> no error only warning and changed the value to 0000:00:00 00:00:00
想知道我可以在 spark 上应用什么设置来获得相同的行为,即应该没有错误并且值应该设置为 0000-00-00 00:00:00。 无论如何在写入表时在火花中应用插入忽略选项。
根据评论,粘贴代码进行仿真
SQL
mysql> create table test (processing_ts timestamp null);
Query OK, 0 rows affected (0.05 sec)
mysql> select * from test;
+---------------------+
| processing_ts |
+---------------------+
| 1997-02-28 10:30:00 |
+---------------------+
1 row in set (0.00 sec)
df = spark.createDataFrame([('1970-01-01 00:00:00',)], ['processing_ts'])
df2 = df.select(f.to_timestamp(df.processing_ts, 'yyyy-MM-dd HH:mm:ss').alias('processing_ts'))
db_host = '127.0.0.1'
DBName = 'test'
jdbc_url = "jdbc:mysql://{}/{}".format(db_host ,DBName)
DBUser = 'XXXXXX'
DBPassword = 'XXXXXXX123'
tbl_name = 'test'
df2.write.format("jdbc").option("url", jdbc_url).option("driver", "com.mysql.jdbc.Driver")\
.option("dbtable", tbl_name).option("user", DBUser).option("password", DBPassword)\
.option("numPartitions",32).mode('append').save()
【问题讨论】:
-
使用
df_to_write.printSchema和您面临问题的 MySQL 列数据类型提供数据框的架构。 -
@ShreyJakhmola 添加了模拟问题的步骤
标签: mysql apache-spark jdbc pyspark databricks