一、准备工作
1、安装cx_Oracle
ttps://pypi.python.org/pypi下查找cx_Oracle并下载
执行安装命令
pip install cx_Oracle-6.0rc1-cp35-cp35m-win_amd64.whl
2、安装ORACLE,并建用户TEST/TEST_lu
二、编写PY文件
import cx_Oracle
conn = cx_Oracle.connect('test/test_lu@orcl1')
print (conn.version)
sql = 'select * from lu_test'
cr=conn.cursor()
cr.execute(sql) #执行sql语句
if cr.
print(" This is Fetchall!")
rs = cr.fetchall() #一次返回所有结果集
print("print all:(%s)" % rs)
print(" print by row:")
for x1 in rs:
print(x1)
print(" This is Fetone!")
cr.execute(sql)
while (1):
rs = cr.fetchone() #一次返回一行
if rs == None: break
print(rs)
#使用参数查询
print(" select with parameter:")
pr = {'id': 1, 'tel': 'test1'}
cr.execute('select * from lu_test where id=:id or name=:tel', pr)
#这里我们将参数作为一个字典来处理的
rs = cr.fetchall()
print(rs)
cr.execute('select * from lu_test where id=:myid or name=:myphone', myid=2, myphone='test2')
#这里我们直接写参数
rs = cr.fetchall()
print(rs)
up=conn.cursor()
up.execute("update lu_test set id=4 where name ='test1'")
conn.commit();
cursor = conn.cursor()
cursor.execute("select * from lu_test")
row = cursor.fetchone()
#print (row[1][0])
#print (row[2][0])
#print (row[0][0])
print(row[1])
row1=cursor.fetchall()
for row_x in row1:
print(row_x)
cursor.close()
conn.close()
三、另外的例子
. 创建一个简单的python文件,测试安装是否成功
- import cx_Oracle
- conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl')
- cursor = conn.cursor ()
- cursor.execute ("select * from dual")
- row = cursor.fetchone ()
- print row[0]
- cursor.close ()
- conn.close ()
4. 下面看一个数据库建表和插入操作
- import cx_Oracle
- conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl')
- cursor = conn.cursor ()
- cursor.execute ("CREATE TABLE TEST(ID INT, COL1 VARCHAR(32), COL2 VARCHAR(32), COL3 VARCHAR(32))")
- cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(1, 'a', 'b', 'c')")
- cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(2, 'aa', 'bb', 'cc')")
- cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(3, 'aaa', 'bbb', 'ccc')")
- conn.commit()
- cursor.close ()
- conn.close ()
5. 下面再来看看查询,查询通常有两种方式:一种是使用cursor.fetchall()获取所有查询结果,然后再一行一行的迭代;另一种每次通过cursor.fetchone()获取一条记录,直到获取的结果为空为止。看一下下面的例子:
- import cx_Oracle
- conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl')
- cursor = conn.cursor ()
- cursor.execute ("SELECT * FROM TEST")
- rows = cursor.fetchall()
- for row in rows:
- print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3])
- print "Number of rows returned: %d" % cursor.rowcount
- cursor.execute ("SELECT * FROM TEST")
- while (1):
- row = cursor.fetchone()
- if row == None:
- break
- print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3])
- print "Number of rows returned: %d" % cursor.rowcount
- cursor.close ()
- conn.close ()