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.
CodePudding user response:
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.