Python Forum
Deleting from a database...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Deleting from a database...
#5
(Aug-20-2020, 11:12 PM)Mort101 Wrote: The above code is literally my first attempt to learn how python works that isn't just a "copy someone else" type deal.

Well done Mort! You are doing fine.

(Aug-22-2020, 06:52 PM)jefsummers Wrote: To get you through the problem at hand, remove where you say IF NOT EXISTS. You will then get an empty table.

This is in the category: "Want to remove a stain from your shirt? Use scissors!". Most often people using a database want to keep their data. Smile

The way to solve this is for every row to be inserted, do a lookup to check if the row is already in the table. If it is: don't insert.
Professionally designed databases and the files providing data will have a primary key. This key will be indexed so the lookup can be very quick. But if you don't have a primary key then you need to check on all columns. Like this:

...
countrecs = "SELECT COUNT(*) FROM TokenTable WHERE ad1 = ? AND ad2 = ? AND ad3 = ?"
insertrecs = "INSERT INTO TokenTable VALUES (?,?,?)"

with open("LE.csv", "r") as file:
    no_records = 0
    for rawrow in file:
        row = rawrow.strip().split(",")
        # number already in database should be 0 or 1.
        nr_already = c.execute(countrecs, row).fetchone()[0]
        # if no rows already in database, insert the row
        if nr_already == 0:
            c.execute(insertrecs, row)
            conn.commit()
            no_records += 1
            print(f"Inserted: {row}")
        else:
            print(f"Already in database: {row}")

c.close()
conn.close()
Reply


Messages In This Thread
Deleting from a database... - by Mort101 - Aug-20-2020, 06:27 PM
RE: Deleting from a database... - by ndc85430 - Aug-20-2020, 07:46 PM
RE: Deleting from a database... - by Mort101 - Aug-20-2020, 11:12 PM
RE: Deleting from a database... - by jefsummers - Aug-22-2020, 06:52 PM
RE: Deleting from a database... - by ibreeden - Aug-23-2020, 08:14 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020