【问题标题】:sending data in dictionary in database using python使用python在数据库中的字典中发送数据
【发布时间】:2012-04-26 01:00:43
【问题描述】:

我有一个使用 wxpython 和 postgresql 作为我的数据库的应用程序。我不知道将数据从 GUI 发送到数据库的正确方法是什么,但我正在做的是将 GUI(txtctrl) 输出存储在字典中并尝试将其发送到 postgresql。我的问题是:有没有办法使用 sqlalchemy 将数据发送到数据库,其中字典键充当 column_fields,字典值充当其值。有没有更优雅的方式来进行 GUI 和数据库之间的数据通信?

【问题讨论】:

  • 好像和这个question类似
  • 我在下面的文章中做了这样的事情:blog.pythonlibrary.org/2011/11/10/…。它可能会帮助您找到自己的方法。
  • @MikeDriscoll:我是你的教程的粉丝并且经常关注它。

标签: python sql wxpython sqlalchemy


【解决方案1】:

假设您在sqlalchemy中使用declaratives,并且您的对象名称是Object,您可以使用:

# I suppose you already have your session somehow...
# If you want to add it to the database
# Assuming you did not change the __init__ method
obj = Object(**data_dictionary_with_keys_matching_column_names)
session.add(obj)

# If you want to issue an update
# obj is already there somehow...
for k, v in data_dictionary_with_keys_matching_column_names.iterkeys():
    setattr(obj, k, v)

session.commit()

仅当您使用 ORM 和声明性时。 (你提到了sqlalchemy,所以我猜它是postgresql还是其他的都不会改变)

编辑:我认为您选择了正确的方法,只需确保您在表单中使用wx.Validators 并将数据存储在字典中,这非常实用。

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多