This question has already been answered:

There are variables u_id and re_id with data.

And there is a table in the User database with branches: id , u_id and re_id .

It is necessary to prohibit adding duplicates, - when data with variables u_id and re_id already exist in the table

 def add_rating(user_id, recipe_id, voice): conn = sqlite3.connect('db.sqlite') c = conn.cursor() c.execute("INSERT INTO User (u_id, re_id) VALUES("+ u_id +","+re_id+")") conn.commit() conn.close() 

check is required, not by a unique id, but by the input data, that is, to check the data in the u_id and re_id tables for uniqueness

Reported as a duplicate by jfs , aleksandr barakin , sercxjo , Pavel Mayorov , Grundy May 3, '16 at 10:19 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

2 answers 2

You need to create a unique index for this table and a combination of fields:

 c.execute("CREATE UNIQUE INDEX User ON t1(u_id, re_id)"); conn.commit() 
  • and if you need to check whether it was added or not, and perform the appropriate function ?? - Kill Noise
  • In case of violation of uniqueness an exception will be thrown. It can be processed. - tonal
  • show by example code - Kill Noise
  • Like this: `` `try: c.execute (" INSERT INTO User (u_id, re_id) VALUES ("+ u_id +", "+ re_id +") ") conn.commit () except sqlite3.Error: print ('Oblom ') conn.rolback () `` `I cannot vouch for the accuracy of names - see the documentation: docs.python.org/3/library/sqlite3.html - tonal
  • the same data still gets into the table - Kill Noise

@tonal prompted the right solution - it allows you to maintain the correctness of the data on the database side

If for some reason you need to transfer this logic to the side of Python, you can proceed as follows: before inserting the data, check if they are in the database. To do this, you can execute a query like SELECT COUNT(*) FROM User WHERE u_id=1 AND re_id=2 . The query returns the number of rows that satisfy the condition. If this is not zero, then such a string is already in the table.