1

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?

Danny
  • 470
  • 1
  • 4
  • 21
  • 1
    Give `cursor.rowcount` a look. I'm not sure what value it will return in the case of the email already existing, though, so you'll need to do some testing. Reference: https://www.python.org/dev/peps/pep-0249/#rowcount – mechanical_meat Apr 28 '21 at 19:12
  • 1
    Seems to be -1 for exists already and 1 for when it creates -- just what I needed! Thanks a bunch. Feel free to suggest as an answer and I'll accept. :) – Danny Apr 28 '21 at 19:16
  • 1
    Sure thing. I just saw that, too, about the `-1` being returned in case the `.execute()` doesn't run. Answer added. Best wishes with the remainder of your project :) – mechanical_meat Apr 28 '21 at 19:18

1 Answers1

1

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

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223