使用cx_Oracle實現數據庫操作


cx_Oracle 是一個Python的擴展模塊,通過使用所有數據庫訪問的模塊通用的數據庫API來是實現Oracle數據庫的查詢和更新。

cx_Oracle的開發歷時十多年,涵蓋了大多數需要在Python中訪問Oracle的客戶的需求。2008年12月,一個新的主要版本解決了早期版本的眾多限制,並增添了對Python3.0和Oracle新推進的一些特性的支持。

下面寫一個是簡單的轉賬例子,附上代碼

配置工作(Oracle.settings.py)

 1 # -*- coding: utf-8 -*-
 2 
 3 import cx_Oracle
 4 
 5 
 6 ##操作Oracle數據庫
 7 class Oracle:
 8     #連接Oracle數據庫
 9     def oracle_Conn(self,oracle_user,oracle_password,oracle_ip,oracle_port,oracle_service_name):
10         print('正在連接Oracle數據庫.......')
11         global conn
12         # 用戶,密碼,oracle數據庫服務名稱(或數據庫系統標識符SID)
13         conn = cx_Oracle.connect(oracle_user, oracle_password, '%s:%s/%s'%(oracle_ip,oracle_port,oracle_service_name),encoding = 'UTF-8')
14 
15 
16     #傳進sql查詢語句
17     def oracle_DQL(self,DQL_sql,params=[],rownums=0,fetchmany=False,fetchall=False):
18         #建立游標
19         # 此代碼確保一旦完成該塊,就將游標關閉並且數據庫已回收資源。此外,任何cursor在塊外使用變量的嘗試都將失敗
20         with conn.cursor(scrollable=True) as cur:
21             cur.execute(DQL_sql,params)
22             if fetchall == True:
23                 query_res = cur.fetchall()
24             elif fetchmany == True:
25                 query_res = cur.fetchmany(rownums)
26             else:
27                 if rownums != 0:
28                     cur.scroll(rownums)
29                 query_res = cur.fetchone()
30         return query_res
31 
32     ##創建表,DDL語句,不用提交
33     def oracle_DDL(self,DDL_sql,bind_params=[]):
34         with conn.cursor() as cur:
35             res = cur.execute(DDL_sql,bind_params)
36         return 'suc'
37 
38     #數據操縱語句,insert,update,delete等
39     def oracle_DML(self,DML_SQL,bind_params=[]):
40         with conn.cursor() as cur:
41             res = cur.execute(DML_SQL,bind_params)
42         conn.commit()
43         return 'suc'
44 
45     def oracle_Conn_Close(self):
46         conn.close()
47         print('Oracle數據庫連接已經關閉.......')
48 
49 '''
50 obj = Oracle()
51 obj.oracle_Conn('back','123','127.0.0.1','1521','orcl')
52 res = obj.oracle_DQL('select * from students')
53 print(res)
54 obj.oracle_Conn_Close()
55 '''
56 
57 '''
58 注意:對於回收站的對象,只支持查詢操作,其他DDL,DML操作均不支持。
59 DQL:數據查詢語句,查詢操作,默認隱式提交
60 DML:數據操縱語句  insert,update,delete  (Manipulation) conn.commit()
61 DCL:數據控制語言  grant  rollback
62 用戶授權或者訪問數據庫的某種特權,並控制數據庫事務發生的時間和效果  
63 DDL:數據定義語言:create 創建數據庫各種對象(隱式提交,不能rollback)
64 '''
View Code

 

創建表(transaction_record_table,bankcard_table,alipay_table)

 1 from examples.oracle_settings import  Oracle
 2 
 3 ##連接oracle數據庫
 4 obj = Oracle()
 5 obj.oracle_Conn('back','123','127.0.0.1','1521','orcl')
 6 
 7 #--------------------------------------------------------------------------------------------------------------------
 8 ##創建表
 9 sql = '''
10 create table transaction_record_table
11 (
12   order_number varchar2(50) not null,
13   transcation_amount number not null,
14   transaction_event  varchar2(50) not null,
15   trader varchar2(50) not null, 
16   Payee varchar2(50) not null,
17   transaction_time  timestamp,
18   status varchar2(20),
19   primary key(order_number)
20 )
21 '''
22 ##創建transaction_record表
23 obj.oracle_DDL(sql)
24 
25 obj.oracle_DDL(sql)
26 #--------------------------------------------------------------------------------------------------------------------
27 
28 sql = '''
29 create table Bankcard_table
30 (
31   bankcard_bid number,
32   owner_name varchar2(20) not null,
33   owner_idcard  varchar2(20) not null unique,
34   bankcard_amount number not null check(bankcard_amount>0),
35   lock_status varchar(10) default 'False' not null,
36   primary key(Bankcard_bid)
37 )
38 '''
39 ##Bankcard
40 obj.oracle_DDL(sql)
41 
42 
43 sql = '''
44 create table alipay_table
45 (
46   alipay_bid number,
47   owner_name varchar2(20) not null,
48   owner_idcard  varchar2(20) not null unique,
49   alipay_amount number(5) not null check(alipay_amount>0 and alipay_amount<100000),
50   lock_status varchar(10) default 'False' not null,
51   primary key(alipay_bid)
52 )
53 '''
54 ##alipay
55 obj.oracle_DDL(sql)
56 #--------------------------------------------------------------------------------------------------------------------
57 
58 obj.oracle_Conn_Close()
View Code

 

插入數據(bankcard_table,alipay_table) 可逐行插入

 1 from examples.oracle_settings import  Oracle
 2 
 3 ##連接oracle數據庫
 4 obj = Oracle()
 5 obj.oracle_Conn('back','123','127.0.0.1','1521','orcl')
 6 
 7 
 8 ##插入數據
 9 #BANKCARD_TABLE
10 insert_sql = """
11 INSERT INTO ALIPAY_TABLE (ALIPAY_BID, OWNER_NAME, OWNER_IDCARD, ALIPAY_AMOUNT,LOCK_STATUS) VALUES (1, '張三', '5456567687787878', 100,'False');
12 INSERT INTO ALIPAY_TABLE(ALIPAY_BID, OWNER_NAME, OWNER_IDCARD, ALIPAY_AMOUNT,LOCK_STATUS) VALUES (2, '小五', '545467676767676', 300,'False');
13 INSERT INTO ALIPAY_TABLE(ALIPAY_BID, OWNER_NAME, OWNER_IDCARD, ALIPAY_AMOUNT,LOCK_STATUS) VALUES (3, '小何', '6676768778787878', 40000,'False');
14 INSERT INTO ALIPAY_TABLE(ALIPAY_BID, OWNER_NAME, OWNER_IDCARD, ALIPAY_AMOUNT,LOCK_STATUS) VALUES (4, '小李', '54545465676767676', 3000,'False');
15 INSERT INTO ALIPAY_TABLE(ALIPAY_BID, OWNER_NAME, OWNER_IDCARD, ALIPAY_AMOUNT,LOCK_STATUS) VALUES (5, '小黑', '4545465656565656', 10,'False');
16 INSERT INTO ALIPAY_TABLE(ALIPAY_BID, OWNER_NAME, OWNER_IDCARD, ALIPAY_AMOUNT,LOCK_STATUS) VALUES (6, '二虎', '4566567676878787', 5666,'False');
17 """
18 #BANKCARD_TABLE
19 obj.oracle_DML(insert_sql)
20 
21 
22 ##alipay_table
23 insert_sql = '''
24 insert into BANKCARD_TABLE (BANKCARD_BID, OWNER_NAME, OWNER_IDCARD, BANKCARD_AMOUNT,LOCK_STATUS) values (1, '張三', '5456567687787878', 3000,'False');
25 insert into BANKCARD_TABLE (BANKCARD_BID, OWNER_NAME, OWNER_IDCARD, BANKCARD_AMOUNT,LOCK_STATUS) values (2, '小黑', '4545465656565656', 10000,'False');
26 insert into BANKCARD_TABLE (BANKCARD_BID, OWNER_NAME, OWNER_IDCARD, BANKCARD_AMOUNT,LOCK_STATUS) values (3, '小明', '5454546565767676', 500,'False');
27 insert into BANKCARD_TABLE (BANKCARD_BID, OWNER_NAME, OWNER_IDCARD, BANKCARD_AMOUNT,LOCK_STATUS) values (4, '小李', '54545465676767676', 3000,'False');
28 insert into BANKCARD_TABLE (BANKCARD_BID, OWNER_NAME, OWNER_IDCARD, BANKCARD_AMOUNT,LOCK_STATUS) values (5, '小五', '545467676767676', 1000,'False');
29 '''
30 obj.oracle_DML(insert_sql)
31 obj.oracle_Conn_Close()
View Code

Alipay_table表

Bankcard_table表

Oracle_case

  1 from examples.oracle_settings import  Oracle
  2 import random,string
  3 
  4 
  5 class Transaction:
  6     #銀行卡到alipay的請求
  7     def bankToAlipay(self,tran_request):
  8         ##連接oracle數據庫
  9         obj = Oracle()
 10         obj.oracle_Conn('back','123','127.0.0.1','1521','orcl')
 11 
 12 
 13         #需要取的數據 >> 銀行卡金額(bankcard_amount) , lock_status
 14         #綁定變量
 15         params = {'idcard':tran_request[0]}
 16         lock_sql = 'select bankcard_amount,lock_status from BANKCARD_TABLE where owner_idcard = :idcard'
 17         res = obj.oracle_DQL(lock_sql,params)
 18 
 19         #如果沒有被交易的話,則可以進行交易,同時需要判斷銀行卡總金額是否大於所需要交易的金額
 20         if res[1] == 'False' and res[0] >= tran_request[-1]:
 21             print('----------------------------------------------------------------------------------------')
 22 
 23             ##首先判斷此隨機生成的訂單編號是否存在,如果存在,則重新生成
 24             for index in range(5):
 25                 order_number = str(random.randint(1000, 10000)) + string.printable[:16]
 26                 params = {'order_number_value':order_number}
 27                 query_sql = 'select * from transaction_record_table where order_number =:order_number_value'
 28 
 29                 query_res = obj.oracle_DQL(query_sql,params)
 30                 if query_res == None:
 31                     break
 32 
 33             print('正在處理用戶銀行卡-alipay的交易[交易編號:%s]........'%order_number)
 34 
 35             lasted_amount = res[0] - tran_request[-1]
 36             update_params = {'a':'True','b':lasted_amount,'c':tran_request[0]}
 37             print(update_params)
 38 
 39             #此時更新狀態為True,原賬戶需要更改金額
 40             update_sql = 'update BANKCARD_TABLE set lock_status = :a ,bankcard_amount = :b where owner_idcard = :c'
 41             result = obj.oracle_DML(update_sql,update_params)
 42 
 43 
 44             ##如果處理成功,則另一個表alipay的金額要更改,而且需要寫入到交易記錄表記錄下來
 45             if result == 'suc':
 46                 #需要獲取alipay_table的金額數量
 47                 target_params = [tran_request[1]]
 48                 sql = 'select alipay_amount from alipay_table where owner_idcard=:1'
 49                 r = obj.oracle_DQL(sql,target_params)
 50 
 51                 ##如果沒有找到此人的話
 52                 if r == []:
 53                     print('沒有找到此用戶.....')
 54                     exit()
 55                 target_amount = tran_request[-1] + r[0]
 56 
 57                 ##目標賬戶需要更改金額
 58                 params = [target_amount,tran_request[1]]
 59                 alipay_update_sql = 'update alipay_table set alipay_amount = :1 where owner_idcard = :2'
 60                 result = obj.oracle_DML(alipay_update_sql,params)
 61 
 62 
 63                 ##如果處理成功,則寫入交易記錄表
 64                 if result != 'suc':
 65                     print('交易處理失敗....')
 66                     exit()
 67                 #獲取當前時間
 68                 sql = 'select systimestamp from dual'
 69                 current_time = obj.oracle_DQL(sql)[0]
 70 
 71 
 72                 ##
 73                 params = [order_number,tran_request[-1],'銀行卡 to alipay',tran_request[0],tran_request[1],current_time,'suc']
 74                 insert_sql = 'insert into transaction_record_table values(:1,:2,:3,:4,:5,:6,:7)'
 75                 result = obj.oracle_DML(insert_sql,params)
 76 
 77                 ##最后需要更改狀態為False
 78                 if result == 'suc':
 79                     params = ['False',tran_request[0]]
 80                     sql = 'update BANKCARD_TABLE set lock_status = :1 where owner_idcard = :2'
 81                     obj.oracle_DML(sql,params)
 82                 obj.oracle_Conn_Close()
 83                 print('處理該用戶交易[交易編號:%s]成功.....'%order_number)
 84                 print('----------------------------------------------------------------------------------------')
 85                 return 'suc'
 86             else:
 87                 print('交易失敗')
 88                 return 'fail'
 89         else:
 90             print('該用戶銀行卡交易已在進行,不可再處理,請等待.........')
 91             return '正在繁忙...'
 92 
 93 
 94 
 95 #source_idcard, target_idcard  source target(銀行卡 支付寶)amount
 96 
 97 #小明 > 小黑
 98 #tran_request = ['5454546565767676','4545465656565656','銀行卡','alipay',100]
 99 #張三 > 二虎
100 tran_request = ['5456567687787878','4566567676878787','銀行卡','alipay',200]
101 result = Transaction().bankToAlipay(tran_request)
102 print(result)
View Code

 

交易請求

tran_request = ['5456567687787878','4566567676878787','銀行卡','alipay',200]

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM