我需要编写一个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