用cxOracle写入数据,慢如蜗牛(cx_Oracle写入慢)

用cx_Oracle写入数据,慢如蜗牛

在Python开发中,我们经常会用到连接Oracle数据库进行数据操作。对于Oracle数据库,可以使用Python的cx_Oracle库连接并执行各种操作。然而,有些开发者在使用cx_Oracle写入数据时,却发现写入速度非常缓慢,好像变成了一只慢如蜗牛的小龟。

下面我们一起来看一下,为什么使用cx_Oracle写入数据会变得缓慢,以及如何解决这个问题。

缓慢现象

在使用cx_Oracle进行大批量写入数据时,可能会出现写入非常缓慢的情况。我们可以试着执行一下下面的代码:

“`python

import cx_Oracle

import time

# 获取Oracle连接

conn = cx_Oracle.connect(username + ‘/’ + password + ‘@’ + ip + ‘:’ + port + ‘/’ + service_name)

# 获取游标

cursor = conn.cursor()

# 写入10万条数据

batch_size = 5000

total_rows = 100000

start_time = time.time()

for i in range(1, total_rows+1):

cursor.execute(“INSERT INTO MY_TABLE VALUES ({}, {})”.format(i, i))

if i % batch_size == 0:

conn.commit()

end_time = time.time()

print(“用时:”, end_time – start_time)


在执行上面的代码时,我们可以发现执行速度非常缓慢,甚至需要几分钟才能够完成10万条数据的写入。这是由于cx_Oracle每次写入都会去连接Oracle服务器,并与服务器进行通信,频繁的连接和通信会导致效率低下。

解决方法

那么,该如何解决cx_Oracle写入数据效率低下的问题呢?下面介绍以下两种方法。

方法一:使用executemany

executemany方法可以在一次连接中一次性写入多行数据,而不必每次都进行连接和通信,这样可以大大提高写入效率。修改上面的代码,使用executemany方法如下:

```python
import cx_Oracle
import time

# 获取Oracle连接
conn = cx_Oracle.connect(username + '/' + password + '@' + ip + ':' + port + '/' + service_name)
# 获取游标
cursor = conn.cursor()
# 写入10万条数据
rows = [(i, i) for i in range(1, 100001)]
batch_size = 5000
total_rows = 100000
start_time = time.time()
cursor.prepare("INSERT INTO MY_TABLE VALUES (:1, :2)")
for i in range(0, total_rows, batch_size):
cursor.executemany(None, rows[i:i+batch_size])
conn.commit()
end_time = time.time()
print("用时:", end_time - start_time)

可以看到,使用executemany方法之后,写入速度非常快。

方法二:使用批量插入

在Oracle中,可以使用INSERT ALL语句一次性插入多条数据。比如:

“`sql

INSERT ALL

INTO mytable (column1, column2, column3) VALUES (‘val1’, ‘val2’, ‘val3’)

INTO mytable (column1, column2, column3) VALUES (‘val4’, ‘val5’, ‘val6’)

INTO mytable (column1, column2, column3) VALUES (‘val7’, ‘val8’, ‘val9’)

SELECT 1 FROM DUAL;


使用批量插入方法,修改上面的代码如下:

```python
import cx_Oracle
import time

# 获取Oracle连接
conn = cx_Oracle.connect(username + '/' + password + '@' + ip + ':' + port + '/' + service_name)
# 获取游标
cursor = conn.cursor()
# 写入10万条数据
rows = [(i, i) for i in range(1, 100001)]
batch_size = 5000
total_rows = 100000
start_time = time.time()
for i in range(0, total_rows, batch_size):
stmt = "INSERT ALL "
end_idx = min(i+batch_size, total_rows)
for j in range(i, end_idx):
stmt += "INTO MY_TABLE VALUES ({}, {}) ".format(rows[j][0], rows[j][1])
stmt += "SELECT 1 FROM DUAL"
cursor.execute(stmt)
conn.commit()
end_time = time.time()
print("用时:", end_time - start_time)

使用批量插入方法也可以达到很快的写入速度。

结语

以上就是使用cx_Oracle写入数据缓慢的一些解决方法。使用executemany方法和批量插入方法可以在一定程度上解决cx_Oracle写入数据缓慢的问题,提高写入效率。


数据运维技术 » 用cxOracle写入数据,慢如蜗牛(cx_Oracle写入慢)