使用cx_python将列表插入到oracle db中会返回非法变量名称/编号

时间:2012-12-10 12:49:24

标签: python cx-oracle

使用内容of this xml example saved on a local file called test.xml,我正在尝试解析内容并使用以下代码插入到我的数据库中:

import cx_Oracle
import re
import os
import xml.etree.ElementTree as ET
from ConfigParser import SafeConfigParser

def db_callmany(cfgFile, sql,params):

    parser = SafeConfigParser()
    parser.read(cfgFile)
    dsn = parser.get('odbc', 'dsn')
    uid = parser.get('odbc', 'user')
    pwd = parser.get('odbc', 'pass')
    try:
        con = None
        con = cx_Oracle.connect(uid , pwd, dsn)
        cur = con.cursor()
        cur.executemany(sql,params)
        con.commit()
    except cx_Oracle.DatabaseError, e:
            print 'Error %s' % e
            sys.exit(1)
    finally:
        if con:
            con.close()

if __name__ == '__main__':
    try:
        cfgFile='c:\\tests\\dbInfo.cfg'
        tree = ET.parse('test.xml')
        root = tree.getroot()
        mdfList = []
        for book in root.findall('book'):
            author = book.find('genre').text
            title = book.find('price').text
            the  = str((author,title))
            mdfList.append(the)

        sql = "INSERT INTO book_table ( GENRE, PRICE )"
        db_callmany(cfgFile,sql,mdfList)

    except KeyboardInterrupt:
        sys.stdout('\nInterrupted.\n')

但是执行此代码我收到以下错误:

Error ORA-01036: illegal variable name/number

Exit code:  1

为了让这段代码有效,我不知道我在这里可以找到什么。

1 个答案:

答案 0 :(得分:2)

CX_Oracle需要占位符,然后是executemany的一系列字典而不是序列序列 - 所以类似于:

mdfList = list()

for book in root.findall('book'):
    Values = dict()
    Values['GENRE'] = book.find('genre').text
    Values['PRICE'] = book.find('price').text
    mdfList.append(Values)

sql = "INSERT INTO book_table (GENRE, PRICE) VALUES (:GENRE, :PRICE)"
db_callmany(cfgFile, sql, mdfList)