【问题标题】:Python: MySQL batch inserting, skip entries where foreign key constraint failsPython:MySQL批量插入,跳过外键约束失败的条目
【发布时间】:2013-10-20 12:06:31
【问题描述】:

我设计了一个带有外键约束的大型数据库,以防止插入损坏的数据,这违反了这些约束。我希望,当我用 Python 插入数据时,它会跳过外键约束失败的每个条目,以便只将“真实”数据插入数据库中。有点像过滤器。但是,只要出现“损坏的”条目,脚本就会停止。有什么办法可以强迫他继续跳过不需要的行吗?

感谢您的帮助!

【问题讨论】:

    标签: python mysql sql batch-file


    【解决方案1】:

    您可以使用INSERT INTO ... SELECT ... 进行条件插入。举个例子:有两个表countrycitycity中的列country_id引用了country中的对应列.

    • country(country_id,name)
    • city(city_id,name,country_id)

    下面的INSERT 语句无条件地插入条目。如果 country 中不存在值为 :country_id 的行,则会失败。

    INSERT INTO city (city_id, name, country_id)
              VALUES (:city_id, :name, :country_id);
    

    以下语句仅在 country 中存在相应行的情况下插入条目。否则,什么都不会发生。

    INSERT INTO city (city_id, name, country_id)
           SELECT :city_id, :name, :country_id
           FROM country
           WHERE country_id=:country_id;
    

    【讨论】:

      【解决方案2】:

      您应该使用处理程序: http://dev.mysql.com/doc/refman/5.1/en/declare-handler.html

      然后选择continue选项

      几个处理程序示例:

      MySQL Stored Procedure Error Handling

      【讨论】:

        猜你喜欢
        • 2021-05-22
        • 2016-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-04
        • 2013-05-29
        • 1970-01-01
        • 2015-04-24
        相关资源
        最近更新 更多