python查詢oracle,使查詢結果類型爲dict

import cx_Oracle
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
dsnStr = cx_Oracle.makedsn("127.0.0.1", "1521", "orcl")


# 將查詢結果轉爲dict
def rows_as_dicts(cursor):
    col_names = [i[0] for i in cursor.description]
    return [dict(zip(col_names, row)) for row in cursor]
def main():
    sql = "SELECT * FROM test limit 10"
    conn = cx_Oracle.connect(user="guanguan", password="guanguan", dsn=dsnStr)
    try:
            cursor = conn.cursor()
            cursor.execute(sql)
            data = rows_as_dicts(cursor)
            cursor.close()
            conn.close()
            print  data
     except Exception, e:
            print e
        
if __name__ == "__main__":   
    main()

#data即爲dict類型
相關文章
相關標籤/搜索