简体   繁体   English

类型错误:需要字符串或字节对象

[英]TypeError: expecting string or bytes object

I am trying to insert CSV data into an Oracle table.我正在尝试将 CSV 数据插入到 Oracle 表中。 But getting error as但是得到错误

TypeError: expecting string or bytes object类型错误:需要字符串或字节对象

Code:代码:

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)

Error:错误:

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

How can I fix the code?我该如何修复代码?

Have resolved the issue.已经解决了问题。

  • First issue is, list cannot be passed as a parameter while using executemany, but list works while using execute第一个问题是,在使用 executemany 时不能将 list 作为参数传递,但在使用 execute 时 list 有效
  • Second issue is, need to bind the source data while inserting.第二个问题是,插入时需要绑定源数据。 However instead of hard coding the binding variables, got the column names and passed the bind variables dynamically, so that any column added or removed in the file can be handled without modifying the code然而,不是对绑定变量进行硬编码,而是获取列名并动态传递绑定变量,这样可以在不修改代码的情况下处理文件中添加或删除的任何列

    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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM