Python 2.7.9 Demo - 019.01.CRUD oracle by cx_Oracle

 select

#coding=utf-8
#!/usr/bin/python
import cx_Oracle;

conn = None;
cursor = None;
try:
    conn = cx_Oracle.connect('username/password@xxx.xxx.xxx.xxx/sid');
    cursor = conn.cursor();
    cursor.execute('select t.empno, t.ename from scott.emp t');
    # 取回的是列表,列表中包含元组
    list = cursor.fetchall();
    print list;

    for record in list:
        print "Record %d is %s!" % (record[0], record[1]);
    
except Exception as e:
    print ('Error : {}'.format(e));
finally:
    cursor.close;
    print 'cursor closed.';
    conn.close;
    print 'connection closed.';
    

 

insert

#coding=utf-8
#!/usr/bin/python
import cx_Oracle;
import time;

conn = None;
cursor = None;
try:
    conn = cx_Oracle.connect('username/password@xxx.xxx.xxx.xxx/sid');
    cursor = conn.cursor();
    tuple = ('1001', 'Nick Huang');
    cursor.execute("insert into scott.emp (empno, ename) values (:1, :2)", tuple);
    conn.commit();
    print 'Insert successfully.';

except Exception as e:
    print ('Error : {}'.format(e));
finally:
    cursor.close;
    print 'cursor closed';
    conn.close;
    print 'connection closed';
    

 

update

#coding=utf-8
#!/usr/bin/python
import cx_Oracle;
import time;

conn = None;
cursor = None;
try:
    conn = cx_Oracle.connect('username/password@xxx.xxx.xxx.xxx/sid');
    cursor = conn.cursor();
    tuple = ('Robin Chen', '1001');
    cursor.execute("update scott.emp t set t.ename = :1 where t.empno = :2", tuple);
    conn.commit();
    print 'Update successfully.';

except Exception as e:
    print ('Error : {}'.format(e));
finally:
    cursor.close;
    print 'cursor closed';
    conn.close;
    print 'connection closed';
    

 

delete

#coding=utf-8
#!/usr/bin/python
import cx_Oracle;
import time;

conn = None;
cursor = None;
try:
    conn = cx_Oracle.connect('username/password@xxx.xxx.xxx.xxx/sid');
    cursor = conn.cursor();
    param_map = {'id' : '1001'};
    cursor.execute("delete from scott.emp t where t.empno = :id", param_map);
    conn.commit();
    print 'Delete successfully.';

except Exception as e:
    print ('Error : {}'.format(e));
finally:
    cursor.close;
    print 'cursor closed';
    conn.close;
    print 'connection closed';
    

 

posted @ 2015-07-02 22:15  nick_huang  阅读(436)  评论(0编辑  收藏  举报