-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSV_to_OracleDB.py
63 lines (54 loc) · 2.14 KB
/
CSV_to_OracleDB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import cx_Oracle
import csv,os
import config as cfg
def create_table():
with cx_Oracle.connect(cfg.username, cfg.password, cfg.dsn, encoding=cfg.encoding) as con:
with con.cursor() as cursor:
try:
cursor.execute("CREATE TABLE TEST (id INTEGER, name VARCHAR(255))")
except Exception as e:
print(e)
def csv_to_oracle():
with cx_Oracle.connect(cfg.username, cfg.password, cfg.dsn, encoding=cfg.encoding) as con:
# create a cursor
with con.cursor() as cursor:
# Predefine the memory areas to match the table definition
# cursor.setinputsizes(None, 25)
# Adjust the batch size to meet your memory and performance requirements
batch_size = 10000
n = os.path.dirname(__file__)
with open( f'{n}/testsp.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
sql = "insert into test (id,name) values (:1, :2)"
data = []
for line in csv_reader:
# print(line)
data.append((line[0], line[1]))
if len(data) % batch_size == 0:
cursor.executemany(sql, data)
data = []
if data:
cursor.executemany(sql, data)
con.commit()
def oracle_output():
with cx_Oracle.connect(cfg.username, cfg.password, cfg.dsn, encoding=cfg.encoding) as con:
# create a cursor
with con.cursor() as cursor:
cursor.execute("SELECT * FROM TEST")
a = cursor.fetchall()
for row in a:
print(row)
def delete_table_if_exists():
with cx_Oracle.connect(cfg.username, cfg.password, cfg.dsn, encoding=cfg.encoding) as con:
# create a cursor
with con.cursor() as cursor:
try:
cursor.execute("Drop table test")
except Exception as e:
print(e)
if __name__ == '__main__':
delete_table_if_exists()
create_table()
csv_to_oracle()
oracle_output()
delete_table_if_exists()