How to overwrite values ​​in a string without increasing id?

  • This question (in different variations) has already been asked many times. Here is a question with two different solutions in my answer . What undesirable results of the second method shown in your case leads to? - jfs
  • "does not work" is not informative. What specific results did you expect and what do you get instead? Create a complete minimal example as in the answer (the example in the answer naturally works as written). In other words, create a minimal reproducible example . - jfs
  • completed the question - Kill Noise
  • This is the first example you tried to answer. I clearly wrote that in this case the second example (UPSERT) should be tried. - jfs
  • inattentive :) but what is UNIQUE INDEX and why is it needed? - Kill Noise

1 answer 1

 import sqlite3 category = 1 directians = "Описания" time = 45 img = 'http://..' author = 'author' title = 'terror' c = sqlite3.connect(':memory:') c.executescript(""" CREATE TABLE content(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,title TEXT NOT NULL, category INTEGER NOT NULL, directians TEXT NOT NULL,time INTEGER,img TEXT,author TEXT, datetime DATETIME DEFAULT CURRENT_TIMESTAMP); CREATE UNIQUE INDEX title_x ON content(title); INSERT INTO content(title,category,directians,time,img,author) values('terror',31,'Описания','33','http://','author'); INSERT INTO content(title,category,directians,time,img,author) values('terror2',32,'Описания','33','http://','author') """) for values in [(title,category,directians,time,img,author)]: with c: cur = c.execute('INSERT OR IGNORE INTO content(title,category,directians,time,img,author) ' 'values(?,?,?,?,?,?)', values) if cur.rowcount == 0: # already exists data = dict(zip("title category directians time img author".split(), values)) cur.execute('update content set title=:title, category=:category,directians=:directians,time=:time,img=:img,author=:author ' 'where title=:title', data) print("БД: Данные были заменены!") else: print("БД: Новые данные добавлены.")