P
P
pypyshka2016-07-14 10:06:41
Python
pypyshka, 2016-07-14 10:06:41

How to properly write data to two SQLite DB tables?

Good afternoon!
Please tell me how to make requests in this case. There are two lists:
a = [('1', '2', '3')]
b = [('a', 'b', 'c'), ('x', 'y', 'z' )]
There are two tables in the database:
table_a:
id | value1 | value2 | value 3 - here id is the primary key with autoincrement
table_b:
id | value1 | value2 | value 3
Accordingly, I make requests:

query_a = "INSERT INTO table_a (value1, value2, value 3) VALUES (?, ?, ?)"
query_b = "INSERT INTO table_b (value1, value2, value 3) VALUES (?, ?, ?)"
cur.executemany(query_a, a)
cur.executemany(query_b, b)

and get:
table_a:
id | value1 | value2 | value 3
1 | 1 | 2| 3
table_b:
id | value1 | value2 | value 3
- | a | b | c
- | x | y | z
And how to do it correctly so that in table_b in the id field the id value from table_a is taken, that is, to get:
table_b:
id | value1 | value2 | value 3
1 | a | b | c
1 | x | y | z

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DDDsa, 2016-07-14
@pypyshka

If I understand the problem correctly,

query_a = "INSERT INTO table_a (value1, value2, value 3) VALUES (?, ?, ?)"
cur.execute(query_a, a[0])
last_id = cur.lastrowid

now the value of the last_id variable can be substituted into the second insert
Or like this:
query_a = "INSERT INTO table_a (value1, value2, value 3) VALUES (?, ?, ?)"
cur.executemany(query_a, a)
cur.execute('SELECT last_insert_rowid()')
last_id = cur.fetchone()[0]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question