python - 即使表不可访问,如何保持对 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()
因此,在插入过程中,当我更改表名时,它只会创建一个异常并退出脚本(因为该表不可用且无法写入)。我想要的是,即使当我重命名并且表不可用时,脚本也需要不断尝试插入。有没有办法做到这一点?
解决方案
这是 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
推荐阅读
- vba - VBA Internet Explorer 11 打开/保存对话框(不是通常的弹出窗口)
- php - 如何使用夹具添加 json
- excel - VBA - 使用嵌套的预声明变量声明和设置范围(运行时错误'91':)
- typescript - 如何添加要输入的属性?
- angular - 如何只返回所有父部分?
- node.js - 约翰尼五的 Npm 错误
- ajax - 无法使用 ajax 从 JAX-RS 端点获得响应
- r - 为每个样本列过滤出具有特定值的行
- logging - 如何在 Jenkins 工作区目录中运行可执行 jar
- javascript - 在带有 django json 响应的 Javascript 中使用 forEach