【问题标题】:while inserting data to oracle from csv file using python getting error ORA-01722: invalid number使用python将数据从csv文件插入oracle时出现错误ORA-01722:无效数字
【发布时间】:2017-08-02 20:36:24
【问题描述】:

我正在尝试将数据加载到 oracle 表中。 here 是我之前的问题,我在其中发布了整个代码,我是如何做到的。

这是代码:

def Create_list():
reader = csv.reader(open("Query_result_combined.csv","r"))
lines=[]
print("Creating a list")
for line in reader:
    lines.append(line)
return lines


def Insert_data():
#connection logic goes here 
print("Connecting Now!!")
#conn = cx_Oracle.connect(connstr)
con = cx_Oracle.connect(db_user,db_password,db_connection_name)
print("Connected to Oracle!!")
lines=Create_list()
cur=con.cursor()
print("Inserting data")
for line in lines:
    cur.execute("INSERT INTO A608232_QUERY_RESULT (InteractionId,QueryId,Score,StartOffsetInMs,EndOffsetInMs,SpeakerRole,QueryIdentity,SpeakerId) VALUES(:1,:2,:3,:4,:5,:6,:7,:8)",line)
con.commit ()
cur.close()
print("completed")

所以我纠正了在回答我的问题时建议的所有 aproches,以便错误已经解决,现在我收到了这个新错误ORA-01722: invalid number

当我使用导入选项将数据直接加载到 oracle 时,数据正在加载。当我尝试读取此代码中的相同文件并尝试推送数据时,我收到此错误。

我打印 lines[:1] 和 lines[:2] 这是我得到的输出:

[['InteractionId', 'QueryId', 'Score', 'StartOffsetInMs', 'EndOffsetInMs', 
'SpeakerRole', 'QueryIdentity', 'SpeakerId']]
[['InteractionId', 'QueryId', 'Score', 'StartOffsetInMs', 'EndOffsetInMs', 
'SpeakerRole', 'QueryIdentity', 'SpeakerId'], ['34118470', '27', '45.63345', 
'89900', '90980', 'U', 'e54fd492-8877-4534-997b-9dbe9a8fbd74', '']]
 Inserting data

谁能指出我在代码中做的错误

【问题讨论】:

    标签: python oracle csv oracle11g


    【解决方案1】:

    您的 csv 文件中有一个标题行,它不是数字数据的一部分。在文件句柄上映射csv.reader 后,您必须使用next(reader) 跳过它。

    另外:使用上下文管理器来确保文件将被关闭,并且不需要循环,只需将行迭代器转换为列表(当第一行已被跳过时)以读取所有行(将更快)

    def Create_list():
        with open("Query_result_combined.csv","r") as f:
           reader = csv.reader(f)
           next(reader)  # skips title line
           return list(lines)  # directly iterate on the rest of the lines
    

    【讨论】:

    • 我没有你所说的不需要循环的部分。 ?如何做到这一点
    • list(lines) 只是创建行列表,就像您执行循环 + 追加一样。但更快更短。我重写了你的Create_list
    • 感谢问题已解决。我也在阅读我的标题,因此数据没有插入到 csv
    猜你喜欢
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2021-10-30
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多