简体   繁体   English

使用python从oracle数据库中的多个表中获取数据并将这些数据插入到另一个表中

[英]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.我想从 Oracle 数据库中的多个表中获取行数。 I have to insert the number of rows into another table using Python.我必须使用 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.如果我想从 20 多个表中获取数据,我必须编写相同的代码 20 次。

For each table, I have to associate with id.对于每个表,我必须与 id 相关联。

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

The output should look like this in table "final2",表“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".第三列代表每个表中的行数,数据应该添加到另一个名为“final2”的表中。

Is there simpler way to insert the row along with ids.是否有更简单的方法来插入行和 ID。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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