简体   繁体   中英

sqlite3 add value a column containing data stored as json

So I'm trying to create a function that create clients and add their ID into the column "client_ids_list" of the company that registered them.

Companies table structure:

    company_id INT,
    vatid INT NOT NULL,
    client_ids_list VARCHAR,
    company_name VARCHAR NOT NULL,
    FOREIGN KEY (company_id) REFERENCES Users(ID)

Code:

def create_client(company_id, username, password, bankaccount, address):
    cursor.execute(''' 
        INSERT INTO Users(username,password,bankaccount,address)
        VALUES(?,?,?,?)''', (username, password, bankaccount, address))
    print("Customer account successfully created")
    client_id = int(cursor.lastrowid)
    print(client_id)
    cursor.execute('''
        INSERT INTO Clients(client_id)
        VALUES(?)''', (client_id,))
    print("Client id added to the Clients table")
    sclient_id = json.dumps(client_id)
    cursor.execute('UPDATE Companies set client_ids_list='+ sclient_id +' WHERE company_id=' + str(company_id))
    print("Client added to the clients ids list")

So the goal is to store the all the clients registered by the company in client_ids_list as a json element. But I have no clue how to do that. I've tried to first retrieve the actual value of the column and store the actual value and the new one into an array and then update the actual value with the array value but without success. Any help is appreciated, I tried to find the answer using the search but without much success.

If your version of Sqlite has the JSON1 extension compiled in, something like:

cursor.execute('''
UPDATE Companies
SET client_ids_list=json_insert(client_ids_list, '$[#]', ?)
WHERE company_id=?
''', (sclient_id,company_id))

(Note use of parameters instead of trying to insert values directly in the query string, which prevents many potential issues.)

The special $[#] path in json_insert() means to append to the end of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM