python3.4连接和读取oracle数据表

想用python连接Oracle并查询数据表,就写了个Demo。参考了以下网址。

Python学习之 cx_Oracle学习记录 一
http://my.oschina.net/bxxfighting/blog/386578
python——连接Oracle数据库
http://www.cnblogs.com/Leo_wl/p/3288402.html
通过SQLite了解数据库操作
http://www.cnblogs.com/fnng/archive/2013/05/26/3099547.html


先说安装cx_Oracle库。

用python连接Oracle需要借助cx_Oracle库。比如cx_Oracle目前最高支持到python3.4,那你安装python3.5就不行。
寻找cx_Oracle库的三个网址:
http://sourceforge.net/projects/cx-oracle/,这个网址貌似停止更新了,其最后更新时刻是2012年。
http://cx-oracle.sourceforge.net/,这个网址貌似是官网,它貌似是实时更新的。
https://pypi.python.org/pypi/cx_Oracle/,这个网址是Python官网的PyPI上的cx_Oracle地址,貌似是实时更新的。
由此可知,某开源库托管在SourceForge/Github上,但是SourceForge/Github上的代码/安装包可能不是最新的,最新的东西可能在其他网站上。所以,我们在找一个开源项目时,可能需要多找几个来源(github、SourceForge、开源项目的官网、其他的一些来源如编程语言的包管理网站、等),然后择新/择需选择下载和使用。
此时(2016年4月16日)我发现PyPI上说可以用pip install cx_Oracle安装cx_Oracle了,但是我实际安装时报错。最后下载的exe安装的它。

然后就是代码了。

安装cx_Oracle

python -m pip install cx_Oracle --upgrade

[python] view plain copy
    1. # Python 3.4.4rc1 (v3.4.4rc1:04f3f725896c, Dec  6 2015, 17:06:10) [MSC v.1600 64 bit (AMD64)] on win32  
    2. # cx_Oracle-5.2.1-11g.win-amd64-py3.4.exe  
    3. import cx_Oracle  
    4.   
    5. print("cx_Oracle.version:", cx_Oracle.version)  
    6. host = "127.0.0.1"  
    7. port = "1521"  
    8. sid = "databasetopaz"  
    9. dsn = cx_Oracle.makedsn(host, port, sid)  
    10. connection = cx_Oracle.connect("scott", "tiger", dsn)  
    11. cursor = cx_Oracle.Cursor(connection)  # 返回连接的游标对象  
    12. print("======")  
    13.   
    14. sql = "select * from user_tablespaces"  
    15. if True:  
    16.     cursor.execute(sql)  
    17.     for i in cursor:  
    18.         print(i)  
    19.     # cursor.execute(sql)  
    20.     # print(len(cursor))# 抛出异常 TypeError: object of type 'cx_Oracle.Cursor' has no len()  
    21.     # 虽然执行了cursor.execute(sql),但是cursor并没有存储查询操作返回的结果集,  
    22.     # 它应该是实时从连接里面获取下一个结果的,所以它并不知道这个SQL总共查询得到了多少行结果。  
    23.     # 所以对它执行len操作显然是错误的。  
    24. print("======")  
    25.   
    26. sql = "select * from user_tables"  
    27. if True:  
    28.     print("cursor1:", cursor)  # 由打印的信息可以知道,cursor.execute语句之前的cursor和该语句之后的cursor是同等地位的。  
    29.     cursor = cursor.execute(sql)  # 所以这个赋值语句是不必要的。另外,上面的例子和下面的例子也都没有执行赋值操作。  
    30.     print("cursor2:", cursor)  
    31.     results = cursor.fetchall()  # 将所有(剩余)的行作为序列的序列。  
    32.     print("len(results):", len(results))  
    33. print("======")  
    34.   
    35. sql = "select * from user_users"  
    36. if True:  
    37.     cursor.execute(sql)  
    38.     while True:  
    39.         result = cursor.fetchone()  # 把查询的结果集中的下一行保存为序列,或者None。  
    40.         if result == None:  
    41.             break  
    42.         print("result:", result)  
    43. print("======")  
    44.   
    45. connection.close()  
    46. print("EXIT") 
原文地址:https://www.cnblogs.com/dpf-learn/p/7905667.html