Python mysql check for duplicate before insert

别说谁变了你拦得住时间么 提交于 2019-12-04 15:25:53

问题


here is the table

CREATE TABLE IF NOT EXISTS kompas_url
(
    id  BIGINT(20) NOT NULL AUTO_INCREMENT,
    url VARCHAR(1000),
    created_date datetime,
    modified_date datetime,
    PRIMARY KEY(id)
)

I am trying to do INSERT to kompas_url table only if url is not exist yet

any idea?

thanks


回答1:


You can either find out whether it's in there first, by SELECTing by url, or you can make the url field unique:

CREATE TABLE IF NOT EXISTS kompas_url
    ...
    url VARCHAR(1000) UNIQUE,
    ...
)

This will stop MySQL from inserting a duplicate row, but it will also report an error when you try and insert. This isn't good—although we can handle the error, it might disguise others. To get around this, we use the ON DUPLICATE KEY UPDATE syntax:

INSERT INTO kompas_url (url, created_date, modified_date)
VALUES ('http://example.com', NOW(), NOW())
ON DUPLICATE KEY UPDATE modified_date = NOW()

This allows us to provide an UPDATE statement in the case of a duplicate value in a unique field (this can include your primary key). In this case, we probably want to update the modified_date field with the current date.

EDIT: As suggested by ~unutbu, if you don't want to change anything on a duplicate, you can use the INSERT IGNORE syntax. This simply works as follows:

INSERT IGNORE INTO kompas_url (url, created_date, modified_date)
VALUES ('http://example.com', NOW(), NOW())

This simply turns certain kinds of errors into warnings—most usefully, the error that states there will be a duplicate unique entry. If you place the keyword IGNORE into your statement, you won't get an error—the query will simply be dropped. In complex queries, this may also hide other errors that might be useful though, so it's best to make doubly sure your code is correct if you want to use it.



来源:https://stackoverflow.com/questions/2564568/python-mysql-check-for-duplicate-before-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!