1

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
);
4
  • Could you use an auto increment column for this purpose? Commented Oct 21, 2016 at 10:27
  • That would be good, I am new to sqlite and I am unsure how to do it correctly though Commented Oct 21, 2016 at 10:31
  • Please post your table structure. Commented Oct 21, 2016 at 10:32
  • Added to original post Commented Oct 21, 2016 at 10:36

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

5 Comments

How can i generate a new id, then check if the id is already used?
thanks, that is a lot of help! But, can you explain what 'data' is. And, am i right to assume that if len(data)==0
If len(data) ==0, then the database search returned no IDs that matched to generated ID?
@MathewWright yes exactly data is the queryset if it's length zero the no ids matches generated id
@MathewWright you are welcome, mark the answer if it was correct .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.