2017-01-26 35 views
1

我使用python 2.7 + Psycopg2 2.6將數據插入Postgresql 9.4數據庫,該數據庫在非常基本的級別上工作正常。創造了一些動態的INSERT查詢,它採取不同的列集合和值從字典(input_cols):如何創建動態插入如果不存在(列數和值不同)Postgresql

sql_template = "insert into tbl ({}) values %s" 
sql = sql_template.format(', '.join(input_cols.keys())) 
params = (tuple(input_cols.values()),) 
cur.execute(sql, params) 

正確的SQL生成:

insert into tbl (col1, col2, ...) values ('val1', 'val2', ...) 

現在想也使用動態SQL生成對於一些INSERT如果不EXIST查詢,但作爲「cur.execute(SQL,則params)」上述輸出由封閉值列表「()」我不能得到它的工作:

sql_template = "insert into tbl ({}) select %s where not exists (select id 
from tbl where id = %s)" 
sql = sql_template.format(', '.join(input_cols.keys())) 
params = (tuple(input_cols.values()), input_cols['col1']) 

不正確的SQL生成:

insert into tbl (col1, col2) select ('val1', 'val2') 
where not exists (select col1 from tbl where id = 'val1') 

我怎麼能輸出('val1', 'val2')沒有(),這樣我可以在一個SELECT xxx, xxx WHERE NOT EXISTS查詢中使用它?

回答

0

使用from (values...

input_cols = {'col1':'val1','col2':'val2'} 
sql_template = """ 
    insert into tbl ({}) 
    select * 
    from (values %s) s 
    where not exists (
     select id 
     from tbl 
     where id = %s 
    ) 
""" 
sql = sql_template.format(', '.join(input_cols.keys())) 
params = (tuple(input_cols.values()), input_cols['col1']) 
print cursor.mogrify(sql, params) 

輸出:

insert into tbl (col2, col1) 
select * 
from (values ('val2', 'val1')) s 
where not exists (
    select id 
    from tbl 
    where id = 'val1' 
) 
+0

大:-)非常感謝這一點,Clodo阿爾內託! – swedishchef