简体   繁体   中英

Update database using variable from csv file in cx_Oracle

Stuck at a point where I'm getting an error ORA-01036: illegal variable name/number when executing the update command in the Oracle database using cx_Oracle & Python3.6.8.

I'm want to use the value of the variable from the CSV file (db_results.csv) and execute the update command.

The db_results.csv file looks like this:

id, order_id, product, Courier, state
01, ORD987, Keyboard, DHL, TX
02, ORD976, Charger, Blue Dart, NY

My code:

con = cx_Oracle.connect("abc/abc@abc")
cur = con.cursor()

with open(r'D:\db_results.csv') as file:
    next(file)
    for line in file:
        x = line.replace('\n', ' ').replace('\r', '')
        columns = x.split(",")
        y = columns[1]
    SQL = "update inventory set model='301547' where order_id = '?'"
    cur.execute(SQL, y)
    con.commit()
con.close()

Is there any specific syntax for UPDATE to be used in cx_Oracle? Tried to find examples for this, but none found so far.

  • ORA-01036 raises due to the wrong type of placeholders for oracle, rather prefer using integers prepended with colons such as :1 , :2

  • Don't forget to trim the second placeholder's value in order to get rid of whitespaces wrapping around the value for y

  • No need to embed the parameters within the DML, rather convert them to a tuple such as (301547, y)

     ... with open(r'D:\db_results.csv') as file: next(file) for line in file: x = line.replace('\n', ' ').replace('\r', '') columns = x.split(",") y = columns[1] SQL = "UPDATE inventory SET model=:1 WHERE order_id = TRIM(:2)" cur.execute(SQL, (301657, y)) con.commit() con.close()

Calling cur.execute() once for each CSV line (as shown in the accepted answer) will be really slow and cannot be recommended.

Instead, look at using cur.executemany() , similar to the code in the cx_Oracle documentation Loading CSV Files into Oracle Database :

with open('testsp.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    sql = "insert into test (id,name) values (:1, :2)"
    data = []
    for line in csv_reader:
        data.append((line[0], line[1]))
        if len(data) % batch_size == 0:
            cursor.executemany(sql, data)
            data = []
    if data:
        cursor.executemany(sql, data)
    con.commit()

In your case the SQL would be the UPDATE statement, and you just need to construct the data variable with your desired values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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