找不到解決方案。我現在傳遞一個元組列表來插入信息,而不是從另一個表中提取,問題就消失了。PostgreSQL false IntegrityError
我目前正在編寫將編輯表的代碼。我有幾行信息可以插入,但是不管順序如何,我都會在第四個元素上獲得IntegrityError
。
這裏是我創建表:
CREATE TABLE segment_speed_live_layer(segment_id INTEGER PRIMARY KEY,
geom GEOMETRY(LINESTRING, 4326),
speed INTEGER);
現在,SEGMENT_ID必須在另一臺匹配,所以它不是也不可能是序貫。下面是函數:
def update_layer():
segment_cursor = connection.cursor()
segment_query = 'SELECT segment_id, speed FROM segment_speed_live ORDER BY segment_id'
exists_cursor = connection.cursor()
exists_query = 'SELECT EXISTS(SELECT 1 FROM segment_speed_live_layer WHERE segment_id=%s)'
insert_cursor = connection.cursor()
insert_query = """INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT %(segment_id)s, geom_way, %(speed)s
FROM other_table
WHERE segment_id=%(segment_id)s"""
update_query = 'UPDATE segment_speed_live_layer SET speed=%(speed)s WHERE segment_id=%(segment_id)s'
segment_cursor.execute(segment_query)
for row in segment_cursor:
segment_id, speed = row
exists_cursor.execute(exists_query, (segment_id,))
exists = exists_cursor.fetchone()[0]
query = update_query if exists else insert_query
print(segment_id, speed, exists)
print(insert_cursor.mogrify(query, {'segment_id': segment_id, 'speed': speed}))
insert_cursor.execute(query, {'segment_id': segment_id, 'speed': speed})
print(insert_cursor.statusmessage)
connection.commit()
如果我的速度命令,它無法在第五的第四個元素代替。它似乎在較低的ID上失敗。這是測試階段,所以我刪除並多次重新創建表,我KNOW
這個表中沒有給定的ID行。
我已閱讀this question和this blog post但他們的解決方案不起作用,因爲我的ID沒有按順序或自動分配。
我現在唯一的想法是去除PRIMARY KEY
約束,但這並不理想。
輸出以供參考:
(243, 69, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 243, geom_way, 69
FROM other_table
WHERE other_table.segment_id=243
INSERT 0 1
(680, 9, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 680, geom_way, 9
FROM other_table
WHERE other_table.segment_id=680
INSERT 0 1
(11599, 42, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 11599, geom_way, 42
FROM other_table
WHERE other_table.segment_id=11599
INSERT 0 1
(16399, 40, False)
INSERT INTO segment_speed_live_layer(segment_id, geom, speed)
SELECT 16399, geom_way, 40
FROM other_table
WHERE other_table.segment_id=16399
多少行'other_table'有哪些? –