【问题标题】:python Storm ORM and avoiding duplicatespython Storm ORM和避免重复
【发布时间】:2012-10-23 17:47:58
【问题描述】:

我是 python 新手,刚开始使用 Storm 和 python 作为基本的 ORM。

我在一个文件中有很多数据并且有一些重复,要识别它们,您可以看到一些行的 id 重复。

我想将它们插入到我的数据库中,我确实将 id 设置为主键,因此它不能有重复项。 如果它是重复的,我希望我的代码忽略在表中插入数据。但它只是失败了_mysql_exceptions.IntegrityError: (1062, "Duplicate entry '75083587476530022' for key 'PRIMARY'")

这是我班级的定义

from storm.locals import *

class Board(object):
  __storm_table__ = 'boards'
  id = Int(primary=True)
  description = Unicode()
  category = Unicode()

  def __init__(self, val): 
    self.id = val['id']
    self.description = val['description']
    self.category = val['category']

我要创建一行:

database = create_database('mysql://root@/mydb') 
store = Store(database)
data = {u'description': u'', u'id': 165366686256470180, u'category': u'Children'}
store.add(Board(data))
store.commit()
store.flush()

我也知道在MYSQL中我可以做什么

ON DUPLICATE KEY UPDATE o

知道如何让 Storm 使用它吗?

【问题讨论】:

    标签: python orm storm-orm


    【解决方案1】:

    我会编写一个 python 脚本,在 SQL 插入之前删除重复。否则,您必须提交每一行,捕获异常并忽略该行。这不好。拥有干净的数据并一次性提交所有数据会更好。 SQL 实际上只关心表操作,而不关心数据完整性。

    【讨论】:

      【解决方案2】:

      如果你想让数据库处理,我建议:

      from MySQLdb import IntegrityError
      # You connected to DB and have your store
      # You loaded your data inside data_list
      for data_row in data_list:
          try:
              store.add(Board(data_row))
              store.flush() # This is enough to raise any DB error
          except IntegrityError:
              continue # You can probably log something here
      store.commit()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多