Home > Back-end >  How can I send into db only if it is not already there
How can I send into db only if it is not already there

Time:12-28

I have a following problem. I would like to send "my_url" to db URLS only if "my_url" is not already in db URLS. I do it using two methods in Python:

    def exist_url(self, my_url): # Returns true/false if my_urls is in the db
        query = """
                SELECT url FROM URLS
                WHERE url=(%s)
                """

        self.cursor.execute(query, my_url)
        return self.cursor.fetchone()

    def insert_url(self, my_url): #sinserts my_url to db
        query = """
                INSERT INTO URLS
                VALUES (%s)
                """

        self.cursor.execute(query, my_url)
        self.connection.commit()

Can I make this two functions into one? That is to check in one query if my_urls already exists in URLS and if not insert it there? Thanks

CodePudding user response:

You could use an insert with not exists logic:

def insert_url(self, my_url): #sinserts my_url to db
    query = """
            INSERT INTO URLS (url)
            SELECT %s
            WHERE NOT EXISTS (SELECT 1 FROM URLS WHERE url = %s)
            """

    self.cursor.execute(query, (my_url, my_url,))
    self.connection.commit()
  • Related