'Try-Except in the For loop

I written the below Try-Except code in a For Loop for Python - PostgreSQL database input. I have a list in .csv file to input into the PostgreSQL database.

1 of the column is primary data enabled. Hence, if the data in the list is duplicated, the Python will throw error.

I written below code and my imagination is the code will run "try" 1st, if "try" error then only jump to the "except" line, for every rows in the list (loop).

But, when I execute my code, once the program go to "except" line, then the program would not go to "try" line again.

Ex.

If my list of data all fresh, the program run and input all rows to database correctly.

If my duplicated data is in the 1st line of the list, the program run to "except" line and the fresh data at the bottom are not input to the database.

As long as there is duplicated data on top, the program will just run into "except" line without go back to "try" line.

Any idea how to improve my code here? Thank you.

My intention is all fresh data need to capture into the database, while there is duplicated, the data row shall be skipped and continue for next line.

        for data in df.iterrows():
            vreceivingdate = str(data[1][0])
            vreceivingtime = str(data[1][1])
            vscanresult = str(data[1][2])
            vinvoicenbr = str(vscanresult[0:6])
            vlotnbr = str(vscanresult[6:9])
            vcasenbr = str(vscanresult[9:12])

            try:
                rec.insertRec(vreceivingdate, vreceivingtime, vscanresult, vinvoicenbr, vlotnbr, vcasenbr)

            except:
                dupDataCounter += 1


Solution 1:[1]

Finally I found the solution for my question. I shall not use Try-Except for this case.

To do what I want to do should use the PostgreSQL function:

"ON CONFLICT DO NOTHING".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ellon d Beginner