我需要編寫一個INSERT語句,首先檢查數據是否已經存在。當前的代碼是內部使用psycopg2連接到一個PostgreSQL數據庫的Python:python psycopg2條件插入語句
sql = """IF NOT EXISTS (SELECT * FROM table \
WHERE col_1 = (%s) AND col_2 = (%s)) \
INSERT INTO table (col1, col2) \
VALUES (%s, %s);"""
data = (col1_data, col2_data, col1_data, col2_data)
try:
CURSOR.execute(sql, data)
DB.commit()
except:
print "Cursor failed INSERT INTO table.\n"
不工作(我沒有做過質量的錯誤處理,所以我沒有得到任何良好的信息)。 於是,我走進psql的,只是嘗試:
IF NOT EXISTS (SELECT * FROM t WHERE c1=d1 AND c2=d2)
INSERT INTO t (c1, c2) VALUES (d1,d2);
,我得到了以下錯誤:
ERROR: syntax error at or near "IF"
LINE 1: IF NOT EXISTS (SELECT * FROM table WHERE c1 = d1...
^
所以我相信我的錯誤是在SQL不是蟒蛇(雖然我可能是錯的),因爲這個工程:
sql = """INSERT INTO t2 (col_0, col_1, col_2) \
VALUES (%s, %s, %s);"""
data = (d1, d2, time.time())
try:
CURSOR.execute(sql, data)
DB.commit()
except:
print "Cursor failed to INSERT INTO t2.\n"
對於表1中,我創建了:
db=> CREATE TABLE table (
col_0 SERIAL PRIMARY KEY,
col_1 varchar(16),
col_2 smallint
);
NOTICE: CREATE TABLE will create implicit sequence "pm_table_ip_id_seq" for serial column "pm_table.ip_id"
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index "pm_table_pkey" for table "pm_table"
CREATE TABLE
我很感激任何幫助和指導。
你確定這兩列不能組成主鍵嗎? – 2012-03-27 19:22:19