【问题标题】:What is the syntax in python to run a oracle query, and have the results inserted into a new oracle table?python中运行oracle查询并将结果插入到新的oracle表中的语法是什么?
【发布时间】:2022-01-08 04:42:00
【问题描述】:

我是 python 新手,但仍然不确定它的所有细节。我已经设法使用 python 在 oracle 中创建了一个新表,但现在我希望能够从以前创建的表中插入 3 个属性。

所以基本上,我的查询目前很简单,例如:

select attribute1, attribute2, attribute 3 from mytable where qc_code = 'F';

我创建的新表也有attribute1、attribute2、attribute 3作为表中唯一的属性。

抱歉,如果这个问题不清楚;我想重点是,如何使用 python 将查询结果插入另一个表。

我使用 python 的原因是因为我计划添加多个查询,但由于我还在学习,我只是想让这个工作。

谢谢。

【问题讨论】:

    标签: python database oracle


    【解决方案1】:

    不要将结果放入 python 中,然后将它们放回数据库中,因为这样效率低下。只需使用INSERT ... SELECT 语句并在数据库中进行所有处理:

    INSERT INTO other_table (attribute1, attribute2, attribute3)
    select attribute1,
           attribute2,
           attribute3
    from   mytable
    where  qc_code = 'F';
    

    【讨论】:

      【解决方案2】:

      来自documentation of cx_Oracle。它显示了如何插入数据和查询数据。所以你想先查询,对数据做一些 python-magic,最后将其插入数据库。

      import cx_Oracle
      
      connection = cx_Oracle.connect(
          user="demopython",
          password="XXXXX",
          dsn="localhost/xepdb1")
      
      print("Successfully connected to Oracle Database")
      
      cursor = connection.cursor()
      
      # Create a table
      
      cursor.execute("""
          begin
              execute immediate 'drop table todoitem';
              exception when others then if sqlcode <> -942 then raise; end if;
          end;""")
      
      cursor.execute("""
          create table todoitem (
              id number generated always as identity,
              description varchar2(4000),
              creation_ts timestamp with time zone default current_timestamp,
              done number(1,0),
              primary key (id))""")
      
      # Insert some data
      
      rows = [ ("Task 1", 0 ),
               ("Task 2", 0 ),
               ("Task 3", 1 ),
               ("Task 4", 0 ),
               ("Task 5", 1 ) ]
      
      cursor.executemany("insert into todoitem (description, done) values(:1, :2)", rows)
      print(cursor.rowcount, "Rows Inserted")
      
      connection.commit()
      
      # Now query the rows back
      for row in cursor.execute('select description, done from todoitem'):
          if (row[1]):
              print(row[0], "is done")
          else:
              print(row[0], "is NOT done")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-25
        • 1970-01-01
        • 2021-10-03
        • 2017-03-24
        • 1970-01-01
        • 2021-01-21
        • 1970-01-01
        • 2012-06-12
        相关资源
        最近更新 更多