繁体   English   中英

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

[英]Trouble inserting data into Postgresql db via Python/psycopg2

使用一种方法(见下),我构建一个插入命令,将一个项目(存储为字典)插入到我的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)

你的字符串不是有效的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)

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

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

例如:msg ='world'Test ='hello%s'%msg

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM