简体   繁体   中英

Fetch data from multiple tables from oracle database using python and insert those data into another table

I want to fetch the number of rows from multiple tables in Oracle Database. I have to insert the number of rows into another table using Python.

I have written the basic code. If I want to fetch the data from 20+ tables, I have to write the same code 20 times.

For each table, I have to associate with id.

table_name = ["abc,"def,"ghi","jkl"] & id_to_associate = [11,22,11,33]

The output should look like this in table "final2",

11, "a", 213, 20-07-21
22, "a", 231, 20-07-21
11, "a", 234, 20-07-21
33, "a", 425, 20-07-21

The third column represents the number of rows in each table and the data should be added to another table named "final2".

Is there simpler way to insert the row along with ids. Below is my code. I want to write a simple code. Can anyone help me with this. Thanks in advance.

sql = "select count(*) from abc"
cursor.execute(sql)
d = cursor.fetchone()[0]
row = [11,"a",213,datetime.datetime.now()]
cursor.execute("INSERT INTO final2 VALUES(:1,:2,:3,:4)",row)
sql = "select count(*) from def"
cursor.execute(sql)
d = cursor.fetchone()[0]
row = [22,"a",231,datetime.datetime.now()]
cursor.execute("INSERT INTO final2 VALUES(:1,:2,:3,:4)",row)

Here's the first way I thought of to do it.

table_name = ["abc","def","ghi","jkl"]
id_to_associate = [11,22,11,33]

queries = [f"select {i} as c1, 'a' as c2, count(*) as c3, sysdate as c4 from {t}" for i, t in zip(id_to_associate, table_name)]
sql = "insert into final2 " + " union ".join(queries)

print(sql)
cursor.execute(sql)
print(f"{cursor.rowcount} rows inserted")

One suggestion: it's generally best practice to specify the column names when doing an insert, just in case the columns get rearranged at some point. You didn't say what your column names are, so I'll just use generic ones as an example:

sql = "insert into final2 (id, sys_code, num_rows, modify_date) " + " union ".join(queries)

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