Python将csv文件加载到Oracle表

时间:2016-10-07 18:16:29

标签: python oracle python-3.x

我是一名蟒蛇初学者。我试图从csv文件中将记录插入到Oracle表中。 csv文件格式:Artist_name,Artist_type,国家/地区。我收到了以下错误:

Error: File "artist_dim.py", line 42, in <module>
    cur.execute(sqlquery)
cx_Oracle.DatabaseError: ORA-00917: missing comma


    import cx_Oracle as cx
    import csv
    import sys

    ##### Step 1 : Connect to Oracle Database#########
    conn_str=u'hr/hr@localhost:1521/PDBORCL'
    conn= cx.connect(conn_str)
    cur=conn.cursor()
    #######################################
    #### Step 2: FETCH LATEST ROW ID FROM ARTIST_DIM###
    query="SELECT nvl(max(row_id)+1,1) from artist_dim"
    cur.execute(query)
    rownum=cur.fetchone()
    x=rownum[0] 

    with open('D:\python\Artist.csv') as f:
        reader=csv.DictReader(f,delimiter=',')
        for row in reader:
            sqlquery="INSERT INTO ARTIST_DIM VALUES (%d,%s,%s,%s)" %(x,row['Artist_name'],row['Artist_type'],row['Country'])
                    cur.execute(sqlquery)
            x=x+1

    conn.commit()

当我尝试读取文件时,它正常工作。

    ##### Just to Read CSV File############################
    with open('D:\python\Artist.csv') as f:
        reader = csv.DictReader(f, delimiter=',')
        for row in reader:
            a="row_id %d Artist : %s type : %s  Country : %s " %(x,row['Artist_name'],row['Artist_type'],row['Country'])
            print(a)
            x=x+1
    print(row['Artist_name'],",",row['Artist_type'],",",row['Country'])  

Also, when I try to insert using hard coded values it is working

    sqlquery1="INSERT INTO ARTIST_DIM VALUES (%d,'Bob','Bob','Bob')" %x
    cur.execute(sqlquery1)

2 个答案:

答案 0 :(得分:1)

在值周围加上引号:

sqlquery="INSERT INTO ARTIST_DIM VALUES (%d,'%s','%s','%s')" %(x,row['Artist_name'],row['Artist_type'],row['Country'])

如果没有引号,则转换为:

sqlquery="INSERT INTO ARTIST_DIM VALUES (1, Bob, Bob, Bob)"

答案 1 :(得分:0)

这是我能做的最有效的方法:

np.expand_dims