【问题标题】:insert list of dictionaries into oracle without unicode symbols using python使用python将字典列表插入没有unicode符号的oracle
【发布时间】:2016-04-27 19:40:59
【问题描述】:

我正在尝试将字典列表作为字符串插入到 Python 中的 Oracle 中。目前,我正在获取一个包含多个字典和列表的列表,然后使用 str() 将其转换,以便我可以将其加载到 oracle 中的 varchar2 列中。我遇到的问题是 unicode 符号被加载到我不想发生的列中。

上传一个字段的一条记录示例

resultRow = str([{u'key1': [{u'key2': 96, u'key3': u'9999', u'key4': u'blah'}, {u'key2': 4, u'key3': u'9991', u'key4': u'brah'}], u'key5': u'1234', u'key6': u'These Are Words'}])
resultList.append(resultRow)

conn = cx_Oracle.connect('mycredentials')
cur = conn.cursor()
sql = 'insert into table1 (fieldname1) values (:1)'
cur.executemany(sql,resultList)
conn.commit()
cur.close()
conn.close()

在oracle表中加载记录

[{u'key1': [{u'key2': 96, u'key3': u'9999', u'key4': u'blah'}, {u'key2': 4, u'key3': u'9991', u'key4': u'brah'}], u'key5': u'1234', u'key6': u'These Are Words'}]

我已经能够遍历列表和字典,但是当我真的只想转储结果时,这是很多额外的处理。

'; '.join('KEY5:'+d['key5']+', '+'KEY6:'+d['key5']+', '+'KEY1:('+', '.join('KEY4:'+x['key4']+', '+'KEY3:'+x['key3']+', '+'KEY2:'+str(x['key2']) for x in d['key1'])+')' for d in resultList)

在oracle表中加载记录

KEY5:1234, KEY6:These Are Words, KEY1:(KEY4:blah, KEY3:9999, KEY2:96, KEY4:brah, KEY3:9991, KEY2:4)

【问题讨论】:

    标签: python json oracle cx-oracle


    【解决方案1】:

    既然标签中已经有 json 为什么不使用它:

    import json
    
    resultList = []
    resultRow = json.dumps([{u'key1': [{u'key2': 96, u'key3': u'9999', u'key4': u'blah'}, {u'key2': 4, u'key3': u'9991', u'key4': u'brah'}], u'key5': u'1234', u'key6': u'These Are Words'}])
    resultList.append(resultRow)
    
    #insert
    
    #fetch
    
    resultRow = json.loads(row.col #or however you get the data from the oracle driver)
    

    【讨论】:

      猜你喜欢
      • 2022-10-18
      • 2016-02-11
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多