遵循这个问题:
\n\n正如 Ilja Everil\xc3\xa4 在他的回答中提到的,我创建了一个表对象:
\n\nfrom sqlalchemy import *\nmetadata = MetaData()\nidTagTable = Table(\'id_tag\', metadata,\n Column(\'id\', String(255), primary_key = True), \n Column(\'category\', String(20), nullable = False),\n Column(\'createddate\', Date, nullable = False),\n Column(\'updatedon\', Date, nullable = False)\n )\nRun Code Online (Sandbox Code Playgroud)\n\n创建表对象后,我更改了插入和更新语句:
\n\ninsert_statement = sqlalchemy.dialects.postgresql.insert(idTagTable)\nupsert_statement = insert_statement.on_conflict_do_update(\n constraint=PrimaryKeyConstraint(\'id\'),\n set_={"updatedon": insert_statement.excluded.updateon,\n "category":insert_statement.excluded.category}\n)\ninsert_values = df.to_dict(orient=\'records\')\nconn.execute(upsert_statement, insert_values)\nRun Code Online (Sandbox Code Playgroud)\n\n现在我收到编程错误:
\n\nTraceback (most recent call last):\n\nFile "<ipython-input-66-0fc6a1bf9c6b>", line 7, in <module>\nconn.execute(upsert_statement, insert_values)\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute\nreturn meth(self, multiparams, params)\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection\nreturn connection._execute_clauseelement(self, multiparams, params)\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement\ncompiled_sql, distilled_params\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context\ncontext)\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception\nexc_info\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause\nreraise(type(exception), exception, tb=exc_tb, cause=cause)\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1159, in _execute_context\ncontext)\n\nFile "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 467, in do_executemany\ncursor.executemany(statement, parameters)\n\nProgrammingError: (psycopg2.ProgrammingError) syntax error at or near \n")"\nLINE 1: ...category) VALUES (\'sports\') ON CONFLICT () DO UPDAT...\n ^\nRun Code Online (Sandbox Code Playgroud)\n\n无法理解为什么我会收到此错误。
\nPrimaryKeyConstraint您用作参数的对象未constraint=绑定到任何表,并且在渲染时似乎不会产生任何结果,如 中所示ON CONFLICT ()。相反,将表的主键作为conflict_target传递,Postgresql将执行唯一索引推断:
upsert_statement = insert_statement.on_conflict_do_update(
constraint=idTagTable.primary_key,
set_={"updatedon": insert_statement.excluded.updateon,
"category":insert_statement.excluded.category}
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10368 次 |
| 最近记录: |