spark dataframe save to SQL table with auto increment column
我在db
中有下表
1 2 3 4 5 6 7 8 9 10 11 12 | +----------------+------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+------------+------+-----+---------+----------------+ | id | bigint(20) | NO | PRI | NULL | auto_increment | | VERSION | bigint(20) | NO | | NULL | | | user_id | bigint(20) | NO | MUL | NULL | | | measurement_id | bigint(20) | NO | MUL | NULL | | | day | timestamp | NO | | NULL | | | hour | tinyint(4) | NO | | NULL | | | hour_timestamp | timestamp | NO | | NULL | | | value | bigint(20) | NO | | NULL | | +----------------+------------+------+-----+---------+----------------+ |
我正在尝试保存包含多个具有以下案例类结构的行的spark数据框:
1 2 3 4 5 6 7 8 | case class Record(val id : Int, val VERSION : Int, val user_id : Int, val measurement_id : Int, val day : Timestamp, val hour : Int, val hour_timestamp : Timestamp, val value : Long ) |
当我尝试使用以下方式通过jdbc驱动程序将数据帧保存到我的sql中时:
1 | dataFrame.insertIntoJDBC(...) |
我收到主键冲突错误:
1 2 3 4 5 | com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) |
我尝试将id = 0设置为所有行的默认值,并且还尝试从案例类中删除id字段,但均无效。
任何人都可以帮忙吗?
谢谢,
墨粉
找到了。
我遇到了SQL <-> Java列类型问题。
根据:https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/guide/jdbc/getstart/mapping.doc.html
bigint sql列在Java中应表示为Long。
将案例类别更改为:
1 2 3 4 5 6 7 8 | case class Record(val id: Long, val VERSION : Long, val user_id : Long, val measurement_id : Long, val day : Timestamp, val hour : Int, val hour_timestamp : Timestamp, val value : Long ) |
并为其工作的数据框中的所有记录设置id = 0。
谢谢