Repeat a command while true or x times (equivalent of while/for loop)

前端 未结 2 1780
野趣味
野趣味 2021-01-28 22:04

I would like to repeat this command as many times as there is still sometextin the field note (several rows from the table itemNotes could

相关标签:
2条回答
  • 2021-01-28 22:49

    You just have your answer in your query:

    UPDATE itemNotes  
    SET 
      note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
    WHERE 
      note LIKE "%sometext%";
    

    It will update all rows that contain sometext in the note field

    UPDATE

    If you want to update the field which has multiple occurrences in different cases and maintain the rest of the text the simplest solution imo is to use regex and for that you need an extension

    UPDATE itemNotes  
    SET 
      note = regex_replace('\bsometext\b',note,'abc')
    WHERE 
      note LIKE "%sometext%";
    
    0 讨论(0)
  • 2021-01-28 22:55

    As recommended by Stephan in his last comment, I used python to do this.

    Here is my code :

    import sqlite3
    import re
    keyword = "sometext"
    replacement = "abc"
    
    db = sqlite3.connect(path_to_sqlite)
    cursor = db.cursor()
    
    cursor.execute(f'SELECT * FROM itemNotes  WHERE note like "%{keyword}%"')
    
    for row in cursor.fetchall():
        row_regex = re.compile(re.escape(keyword), re.IGNORECASE)
        row_regex_replaced = row_regex.sub(replacement, row[2])
    
        rowID = row[0]
        sql = "REPLACE INTO itemNotes (itemID,note) VALUES (?,?)"
        data = (rowID, row_regex_replaced)
        cursor.execute(sql, data)
        db.commit()
    
    0 讨论(0)
提交回复
热议问题