TypeError:期望字符串或字节对象

时间:2019-02-23 16:29:14

标签: python cx-oracle


嗨,
Am试图将csv数据插入到oracle表中。但是出现错误

  

TypeError:期望字符串或字节对象

with open('file.csv', 'r') as srcfile:
reader = csv.reader(srcfile, dialect = 'fileProperties')
header = next(reader)
header = ", ".join(str(h) for h in header)
insert = 'insert into table (' + header + ') values ('
#print(insert) 

for row in reader:
    data = [insert + str(row).strip("[]") + ');']

cur.prepare(data)
cur.execute(data)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-154-8814eee5c788> in <module>
  1 #cur.prepare(data)
----> 2 cur.execute(data)

TypeError: expecting string or bytes object

如果代码有误,请指导我。

1 个答案:

答案 0 :(得分:0)

已解决了该问题。

*第一个问题是,在使用executemany时不能将list作为参数传递,但是list   在使用execute时有效
*第二个问题是,插入时需要绑定源数据。但是,而不是困难   对绑定变量进行编码,获取列名并传递绑定变量   动态地进行操作,因此无需处理文件中添加或删除的任何列   修改代码

with open('G:\Project\ETL\data\CME.csv', 'r') as srcfile:
reader = csv.reader(srcfile, dialect = 'fileProperties')
header = next(reader)
columns = ", ".join(str(h) for h in header)
length = len(next(reader))
bind = []
data = []

for binds in range(1, length+1):
    bind.append(':' + str(binds))


insert = 'insert into ledger_source_python (' + columns + ') values (' + ", ".join(str(l) for l in bind) + ')' 

for row in reader:
    data.append(row)

cur.executemany(insert, data)
con.commit()

感谢您的所有评论。