为什么我得到" FROM表达预期"来自SQLAlchemy,当我试图更新表中的行时?

时间:2014-12-06 20:24:06

标签: python python-3.x sqlalchemy

我尝试更新表格中的一行,但我收到了参数错误。

以下是代码:

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))更新行,我就会收到错误。

1 个答案:

答案 0 :(得分:3)

update将表名作为其第一个arg,而不是表类的实例。您想要更新什么价值?例如,如果要更新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)
...