2011-08-31 42 views
3

使用一種方法(參見下面),我構建了一個插入命令來將一個項目(作爲字典存儲)插入到我的postgresql數據庫中。雖然,當我將該命令傳遞給cur.execute時,我得到一個語法錯誤。我真的不知道爲什麼會出現這個錯誤。通過Python/psycopg2插入數據到Postgresql數據庫的問題

>>> print insert_string 
"""INSERT INTO db_test (album, dj, datetime_scraped, artist, playdatetime, label, showblock, playid, showtitle, time, station, source_url, showgenre, songtitle, source_title) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""", (item['album'], item['dj'], item['datetime_scraped'], item['artist'], item['playdatetime'], item['label'], item['showblock'], item['playid'], item['showtitle'], item['time'], item['station'], item['source_url'], item['showgenre'], item['songtitle'], item['source_title']) 

>>> cur.execute(insert_string) 

psycopg2.ProgrammingError: syntax error at or near """"INSERT INTO db_test (album, dj, datetime_scraped, artist, playdatetime, label, showblock, playid, showtitle, time, station, source_url, showgenre, songtitle, source_title) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"""" 
    LINE 1: """INSERT INTO db_test (album, dj, datetime_scraped, artis... 

下面是INSERT命令而更多的 「眼球友好」 的版本:

"""INSERT INTO db_test (album, dj, datetime_scraped, artist, playdatetime, label, showblock, playid, showtitle, time, station, source_url, showgenre, songtitle, source_title) 
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""", 
    (item['album'], item['dj'], item['datetime_scraped'], item['artist'], item['playdatetime'], item['label'], item['showblock'], item['playid'], item['showtitle'], item['time'], item['station'], item['source_url'], item['showgenre'], item['songtitle'], item['source_title']) 

用於構建插件的方法:

def build_insert(self, table_name, item): 
    if len(item) == 0: 
     log.msg("Build_insert failed. Delivered item was empty.", level=log.ERROR) 
     return '' 

    #itemKeys = item.keys() 
    itemValues = [] 
    for key in item.keys(): # Iterate through each key, surrounded by item[' '], seperated by comma 
     itemValues.append('item[\'{theKey}\']'.format(theKey=key)) 

    sqlCommand = "\"\"\"INSERT INTO {table} ({keys}) VALUES ({value_symbols});\"\"\", ({values})".format(
     table = table_name, #table to insert into, provided as method's argument 
     keys = ", ".join(item.keys()), #iterate through keys, seperated by comma 
     value_symbols = ", ".join("%s" for key in itemValues), #create a %s for each key 
     values = ", ".join(itemValues)) 

    return sqlCommand 

~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

編輯:

我使用了Gringo Suaves的建議,除了對build_insert方法進行了小小改動外(根據存在的鍵的數量,根據需要創建了許多%s符號。

def build_insert(self, table_name, item): 
    if len(item) == 0: 
    log.msg("Build_insert failed. Delivered item was empty.", level=log.ERROR) 
    return '' 

    keys = item.keys() 
    values = [ item[k] for k in keys] # make a list of each key 

    sqlCommand = 'INSERT INTO {table} ({keys}) VALUES ({value_symbols});'.format(
    table = table_name, #table to insert into, provided as method's argument 
    keys = ", ".join(keys), #iterate through keys, seperated by comma 
    value_symbols = ", ".join("%s" for value in values) #create a %s for each key 
    ) 
    return (sqlCommand, values) 

回答

2

您的字符串不是有效的SQL語句,它包含大量的python cruft。

我想我已經固定的方法:

def build_insert(self, table_name, item): 
    if len(item) == 0: 
     log.msg('Build_insert failed. Delivered item was empty.', level=log.ERROR) 
     return '' 

    keys = item.keys() 
    values = [ item[k] for k in keys ] 

    sqlCommand = 'INSERT INTO {table} ({keys}) VALUES ({placeholders});'.format(
     table = table_name, 
     keys = ', '.join(keys), 
     placeholders = ', '.join([ "'%s'" for v in values ]) # extra quotes may not be necessary 
    ) 

    return (sqlCommand, values) 

隨着一些虛擬的數據,它返回下面的元組。我加了幾個換行符爲清楚:

("INSERT INTO thetable (album, dj, datetime_scraped, artist, 
    playdatetime, label, showblock, playid, songtitle, time, station, 
    source_url, showgenre, showtitle, source_title) VALUES ('%s', '%s', 
    '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 
    '%s', '%s');", 
    ['album_val', 'dj_val', 'datetime_scraped_val', 'artist_val', 
    'playdatetime_val', 'label_val', 'showblock_val', 'playid_val', 
    'songtitle_val', 'time_val', 'station_val', 'source_url_val', 
    'showgenre_val', 'showtitle_val', 'source_title_val'] 
) 

最後,把它傳遞給cur.execute():

instr, data = build_insert(self, 'thetable', item) 
cur.execute(instr, data) 
+0

除了在代碼中僅使用一個(%s)(因爲插入了多個值),這非常有效。我已將最終代碼添加到頂部。謝謝! – alukach

+0

好的,我之前有過多個,但我把你的鏈接看得太直接了。 –

+0

剛回來。 –

-2

您缺少'%'(在傳遞查詢參數之前)。

基本上你必須確保'%s'被實際值取代。

例如: 味精= '世界' 測試= '你好%s' 的%MSG

'%' 將替換與任何存儲在變量msg的佔位符。

您可以在錯誤消息中看到psycopg正在使用實際的'%s'獲取查詢字符串,這就是爲什麼它不會運行。

+3

我不認爲這是它。從我對SQL語句知之甚少,使用字符串參數插值(%)是一個很大的禁忌,可以打開SQL注入([說明])(http://initd.org/psycopg/docs/usage.html #的 - 問題與-的查詢參數))。我基於我的命令格式化他們的演示([這部分](http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries))。 – alukach

相關問題