使用 python 从 oracle 数据库中获取多个 table 的数据并将这些数据插入另一个 table
Fetch data from multiple tables from oracle database using python and insert those data into another table
我想从 Oracle 数据库中的多个 table 中获取行数。我必须使用 Python.
将行数插入另一个 table
基本代码我写好了。如果我想从 20+ tables 中获取数据,我必须编写相同的代码 20 次。
对于每个table,我都必须关联id。
table_name = ["abc,"def,"ghi","jkl"] & id_to_associate = [11,22,11,33]
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
第三列表示每个 table 中的行数,数据应添加到另一个名为“final2”的 table。
是否有更简单的方法来插入带有 ID 的行。下面是我的代码。我想写一个简单的代码。谁能帮我这个。提前致谢。
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)
这是我想到的第一种方法。
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")
一个建议:通常最佳做法是在执行插入时指定列名,以防万一列在某个时候被重新排列。你没有说你的列名是什么,所以我就用通用的作为例子:
sql = "insert into final2 (id, sys_code, num_rows, modify_date) " + " union ".join(queries)
我想从 Oracle 数据库中的多个 table 中获取行数。我必须使用 Python.
将行数插入另一个 table基本代码我写好了。如果我想从 20+ tables 中获取数据,我必须编写相同的代码 20 次。
对于每个table,我都必须关联id。
table_name = ["abc,"def,"ghi","jkl"] & id_to_associate = [11,22,11,33]
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
第三列表示每个 table 中的行数,数据应添加到另一个名为“final2”的 table。
是否有更简单的方法来插入带有 ID 的行。下面是我的代码。我想写一个简单的代码。谁能帮我这个。提前致谢。
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)
这是我想到的第一种方法。
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")
一个建议:通常最佳做法是在执行插入时指定列名,以防万一列在某个时候被重新排列。你没有说你的列名是什么,所以我就用通用的作为例子:
sql = "insert into final2 (id, sys_code, num_rows, modify_date) " + " union ".join(queries)