使用 python 自动递增 table 列

Auto increment a table column using python

Hive 我有一个 table 叫做测试。在此 table 我想要 5 列。

ID, start_time, end_time, min_value, max_value.

现在使用 Pyspark 我想填充这个 table。

我在 python 文件中的操作如下:

start_time='4/5/2017'
end_time='5/4/2017'
min_value='1'
max_value='100'

sqlContext.sql("insert into table testing.test select '{}','{}','{}','{}','{}'".format(id,start_time,end_time,min_value,max_value))

在上面的脚本中 start_time、end_time、min_value、max_value 我将获取这些值作为脚本的一部分。

现在我想要的是该列应该是 Auto incremented 当执行插入语句时应该有 id 增值。

是否可以使用 python?如果是那么

如何在我的脚本

中对列 ID 进行自动递增

你可以简单地创建一个 ID 变量,并添加到它,每当你也执行插入命令时,比如:

id = 1 #outside of the loop or function, possibly make it a global variable

#some loop or function#

sqlContext.sql(....)

id = id + 1

如果您要多次填充该数据库(这很可能),您应该从数据库的 latest/highest 值中获取 id 变量,这样它就不会重复; )