Mathew Wright
Mathew Wright

Reputation: 15

Python sqlite3 generate unique identifier

I am trying to add values to a 'pending application table'. This is what I have so far:

    appdata = [(ID,UNIQUE_IDENTIFIER,(time.strftime("%d/%m/%Y"),self.amount_input.get(),self.why_input.get())]

    self.c.execute('INSERT into Pending VALUES (?,?,?,?,?)', appdata)
    self.conn.commit()

I need to set a value for 'UNIQUE_IDENTIFIER', which is a primary key in a sqlite database.

How can I generate a unquie number for this value?

CREATE TABLE Pending (
    ID          STRING REFERENCES StaffTable (ID),
    PendindID   STRING PRIMARY KEY,
    RequestDate STRING,
    Amount      TEXT,
    Reason      TEXT
);

Upvotes: 1

Views: 5796

Answers (1)

Hisham Karam
Hisham Karam

Reputation: 1318

two ways to do that:

1-First

in python you can use uuid module example:

>>> import uuid
>>> str(uuid.uuid4()).replace('-','')
'5f202bf198e24242b6a11a569fd7f028'

note : a small chance to get the same str so check for object exist with the same primary key in the table before saving

this method uuid.uuid4() each time return new random

for example:

>>> ID=str(uuid.uuid4()).replace('-','')
>>>cursor.execute("SELECT * FROM Pending WHERE PendindID = ?", (ID,))
>>>if len(data)==0:
      #then save new object as there is no row with the same id
   else:
       #create new ID

2-second

in sqlite3 make a composite primary key according to sqlite doc

CREATE TABLE Pending (
  column1, 
  column2, 
  column3, 
  PRIMARY KEY (column1, column2)
);

Then make sure of uniqueness throw unique(column1, column2)

Upvotes: 2

Related Questions