首页 > 解决方案 > 即使表不可访问,如何保持对 Oracle 表的持续写入?

问题描述

我正在尝试将多条记录连续插入到一个 Oracle 表中。我在下面写了python脚本。

import cx_Oracle
import config

connection = None
try:
    # Make a connection
    connection = cx_Oracle.connect(
        config.username,
        config.password,
        config.dsn,
        encoding=config.encoding)

    # show the version of the Oracle Database
    print(connection.version)

    # Insert 20000 records
    for i in range(1, 20001):
        cursor = connection.cursor()
        sql = "INSERT into SCHEMA.ABC (EVENT_ID, EVENT_TIME) VALUES( "+ str(i)+" , CURRENT_TIMESTAMP)"
        cursor.execute(sql)
        connection.commit()
except cx_Oracle.Error as error:
    print(error)
finally:
    if connection:
        connection.close()
    

因此,在插入过程中,当我更改表名时,它只会创建一个异常并退出脚本(因为该表不可用且无法写入)。我想要的是,即使当我重命名并且表不可用时,脚本也需要不断尝试插入。有没有办法做到这一点?

标签: pythonpython-3.xoracleoracle11g

解决方案


这是 Ptit Xav 所说的一个例子。我添加了一些代码以在最大重试次数后退出,因为这通常是可取的。

# Insert 20000 records
for i in range(1, 20001):
    retry_count = 0
    data_inserted = False
    while not data_inserted:
        try:
            cursor = connection.cursor()
            sql = "INSERT into SCHEMA.ABC (EVENT_ID, EVENT_TIME) VALUES( "+ str(i)+" , CURRENT_TIMESTAMP)"
            cursor.execute(sql)
            connection.commit()
            data_inserted = True
        except cx_Oracle.Error as error:
            print(error)
            time.sleep(5) # wait for 5 seconds between retries
            retry_count += 1
            if retry_count > 100:
               print(f"Retry count exceeded on record {i}, quitting")
               break
    else:
        # continue to next record if the data was inserted
        continue
    # retry count was exceeded; break the for loop.
    break

有关逻辑的更多解释,请参见此答案。while... else


推荐阅读