Python import/insert 使用 cx_Oracle 的 Oracle BD 中的 CSV(没有 headers)
Python import/insert a CSV (without headers) in a Oracle BD using cx_Oracle
任何人都可以建议一种使用 cx_Oracle 将 CSV 文件导入 Oracle BD 的方法。下面的代码有效,但我必须在 运行 下面的 Python 脚本之前手动删除第 1 行的 CSV headers 列。有没有办法更改代码以忽略 CSV 文件的第 1 行?
import cx_Oracle
import csv
connection = cx_Oracle.connect(USER,PASSWORD,'adhoc_serv')#DADs
cursor = connection.cursor()
insert = """
INSERT INTO MUK (CODE, UNIT_NAME, GROUP_CODE, GROUP_NAME,)
VALUES(:1, :2, :3, :4)"""
# Initialize list that will serve as a container for bind values
L = []
reader = csv.reader(open(r'C:\Projects\MUK\MUK_Latest_PY.csv'),delimiter=',')
for row in reader:
L.append(tuple(row))
# prepare insert statement
cursor.prepare(insert)
print insert
# execute insert with executemany
cursor.executemany(None, L)
# report number of inserted rows
print 'Inserted: ' + str(cursor.rowcount) + ' rows.'
# commit
connection.commit()
# close cursor and connection
cursor.close()
connection.close()
如果您想简单地忽略 CSV 文件的第 1 行,可以通过在创建 reader 后立即执行此操作轻松实现:
next(reader)
这只会从 CSV 文件中获取第一行并将其丢弃。
任何人都可以建议一种使用 cx_Oracle 将 CSV 文件导入 Oracle BD 的方法。下面的代码有效,但我必须在 运行 下面的 Python 脚本之前手动删除第 1 行的 CSV headers 列。有没有办法更改代码以忽略 CSV 文件的第 1 行?
import cx_Oracle
import csv
connection = cx_Oracle.connect(USER,PASSWORD,'adhoc_serv')#DADs
cursor = connection.cursor()
insert = """
INSERT INTO MUK (CODE, UNIT_NAME, GROUP_CODE, GROUP_NAME,)
VALUES(:1, :2, :3, :4)"""
# Initialize list that will serve as a container for bind values
L = []
reader = csv.reader(open(r'C:\Projects\MUK\MUK_Latest_PY.csv'),delimiter=',')
for row in reader:
L.append(tuple(row))
# prepare insert statement
cursor.prepare(insert)
print insert
# execute insert with executemany
cursor.executemany(None, L)
# report number of inserted rows
print 'Inserted: ' + str(cursor.rowcount) + ' rows.'
# commit
connection.commit()
# close cursor and connection
cursor.close()
connection.close()
如果您想简单地忽略 CSV 文件的第 1 行,可以通过在创建 reader 后立即执行此操作轻松实现:
next(reader)
这只会从 CSV 文件中获取第一行并将其丢弃。