我正在尝试更新表中的一行,但收到参数错误。
这是代码:
inventory_host = InventoryHost(ipv4_addr=ipv4, ipv6_addr=ipv6, macaddr=mac, host_name=name)
try:
session.add(inventory_host)
session.commit()
except sqlalchemy.exc.IntegrityError:
session.execute(update(inventory_host))
session.commit()
session.close()
这是我收到的错误:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "perception.py", line 77, in <module>
main()
File "perception.py", line 66, in main
modules.nmap_parser.parse_nmap_xml(nmap_xml)
File "/Users/arozar/Documents/Scripts_Code/Python-Projects/perception/modules/nmap_parser.py", line 128, in parse_nmap_xml
session.execute(update(inventory_host))
File "<string>", line 2, in update
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/sqlalchemy/sql/dml.py", line 668, in __init__
ValuesBase.__init__(self, table, values, prefixes)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/sqlalchemy/sql/dml.py", line 183, in __init__
self.table = _interpret_as_from(table)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/sqlalchemy/sql/selectable.py", line 41, in _interpret_as_from
raise exc.ArgumentError("FROM expression expected")
sqlalchemy.exc.ArgumentError: FROM expression expected
session.add(inventory_host)
适用于 inventory_host 表中的新主机,但一旦我尝试使用 session.execute(update(inventory_host))
更新该行我收到错误。
最佳答案
update
将表名称作为其第一个参数,而不是表类的实例。您想要更新什么值?例如,如果您想更新 host_name,您可以这样做:
from sqlalchemy import update
# Ideally, just use your primary key(s) in your where clause; I'm not sure what they are
stmt = (update(InventoryHost).where(ipv4_addr=ipv4, ipv6_addr=ipv6, macaddr=mac)
.values(host_name=name) # updates the host_name, for example
session.execute(stmt)
...
关于python - 当我尝试更新表中的行时,为什么会从 SQLAlchemy 得到 "FROM expression expected"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27336095/