回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>使用一个方法(见下图),我构建了一个insert命令,将一个条目(存储为字典)插入到我的postgresql数据库中。不过,当我把命令传给当前执行我得到一个语法错误。我真的不知道为什么会发生这个错误。在</p>
<pre><code>>>> 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...
</code></pre>
<p>下面是这个insert命令的一个更“友好”的版本:</p>
^{pr2}$
<p>用于生成插入的方法:</p>
<pre><code>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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>('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
</code></pre>
<p>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</p>
<p>编辑:</p>
<p>我使用了Gringo Suaves的建议,除了对build_insert方法做了一些小的更改(根据存在的键的数量,根据需要创建尽可能多的%s符号)。在</p>
<pre><code>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)
</code></pre>