gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:27:16 26 4
gpt4 key购买 nike

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

我想我已经修复了这个方法:

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)

关于python - 无法通过 Python/psycopg2 将数据插入 Postgresql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7263362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com