Skip to content
Advertisement

Python/SQL/pydobc: Get result of if operation for counter?

I’m running the following code to add emails to a database table if they do not already exist. I’d like to be able to count the emails that are added and the ones that already existed.

import pyodbc
emails = [# a list of emails]
new_count = 0
existed_already_count = 0
for email in emails:
        cursor.execute(f"""
            IF NOT EXISTS (
                SELECT * 
                FROM TableName
                WHERE email = '{email}'
            )
            BEGIN
               INSERT INTO TableName(email)
               VALUES ('{email}')
            END
        """)
        # new_count OR existed_already_count += 1

I’ve tried checking the cursor.description after each loop, but it returns None whether the item existed or not. Is there a way to do this?

Advertisement

Answer

This was originally posted as a comment.

Give cursor.rowcount a look. I’m not 100% sure what value it will return in the case of the email already existing, it should return -1, though per the documentation: https://www.python.org/dev/peps/pep-0249/#rowcount

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement