python - 当我尝试更新表中的行时,为什么会从 SQLAlchemy 得到 "FROM expression expected"?

标签 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)) 更新该行我收到错误。

最佳答案

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/

相关文章:

python - numpy.minimum() 的返回类型?

python - pygame.mixer.music.play() 无法识别 Fast Tracker(.xm 音乐格式)重复位置

python-3.x - 使用 Pandas 仅加载 CSV 文件的前两列

python - Pandas 获取列包含所有行中的字符

python - 将 Flask SQLAlchemy 模型与常规 SQLAlchemy 结合使用

python - 我在 python 中的函数正在被调用,即使我只是定义它

python - 从字符串创建二维字典

python - 将 2 个嵌套的字典值组合成一个 Python

使用 MID() 的 Python SQLALCHEMY 查询

python - Heroku SQLAlchemy 数据库不存在