无法通过Python / psycopg2将数据插入Postgresql数据库

时间:2011-08-31 21:01:22

标签: python postgresql insert

使用方法(参见下图),我构建一个insert命令,将一个项目(存储为字典)插入到postgresql数据库中。虽然,当我将该命令传递给cur.execute时,我收到语法错误。我真的不知道为什么会出现这个错误。

>>> 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 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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:-2)

您缺少'%'(在传递查询参数之前)。

基本上你必须确保'%s'被实际值替换。

例如:     msg ='世界'     Test ='hello%s'%msg

'%'将使用变量msg中存储的内容替换占位符。

你可以在错误消息中看到psycopg正在获取具有实际'%s'的查询字符串,这就是为什么它不能运行。