使用一个方法(见下图),我构建了一个insert命令,将一个条目(存储为字典)插入到我的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命令的一个更“友好”的版本:
^{pr2}$用于生成插入的方法:
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。在
我想我已经修好了方法:
对于一些伪数据,它返回以下元组。为了清楚起见,我添加了一些新行:
^{pr2}$最后,把它传给当前执行():
缺少“%”(在为查询传递参数之前)。在
基本上,您必须确保“%s”被实际值替换。在
例如: msg='世界' Test='你好%s'%msg
“%”将用变量msg中存储的内容替换占位符。在
您可以在error msg中看到psycopg正在获取带有实际“%s”的查询字符串,这就是它无法运行的原因。在
相关问题 更多 >
编程相关推荐