我有以下代碼。在第一個函式中創建資料庫連接。在最后一個函式中,我將資料插入到表中。由于我沒有提交記錄,因此資料庫中沒有提交資料。如果我將游標和連接都回傳為,,return cur, conn我如何在另一個函式中訪問它們
import cx_Oracle
class transformation():
def oracle_conn(self):
con = cx_Oracle.connect('user/password@localhost:1521/xe')
cur = con.cursor()
return cur
def extract(self):
data = self.oracle_conn().execute('select * from employees').fetchall()
return [(row) for row in data]
def load(self):
values = self.expression()
query = 'INSERT INTO hr.employees_python (EMPLOYEE_ID, NAME, EMAIL, ' \
'PHONE_NUMBER, HIRE_DATE, JOB_ID, SALARY, MONTH, ' \
'DAY, YEAR) values (:0, :1, :2, :3, :4, :5, :6, :7, :8, :9)'
self.oracle_conn().executemany(query, values)
a = transformation()
a.load()
任何建議都會有所幫助。
uj5u.com熱心網友回復:
使類的 cur 和 conn 屬性
import cx_Oracle
# class names should be capitalized
# no need for parenthesis if you are not inheriting
class Transformation:
# You might want a constructor to pass parameters
def __init__(self):
self.con = None
self.cur = None
def oracle_conn(self):
# now cur and con are attributes of the class,
# so you don't actually need to return them
self.con = cx_Oracle.connect('user/password@localhost:1521/xe')
self.cur = self.con.cursor()
def extract(self):
# you can access cur and con here by doing
# self.cur
# self.con
# just call oracle_conn() and then you can access self.con
# but # you might not want to call oracle_con everytime.
self.oracle_conn()
data = self.con.execute('select * from employees').fetchall()
return [(row) for row in data]
def load(self):
# you can access cur and con here by doing
# self.cur
# self.con
# here you are using self.expression() which is not defined
values = self.expression()
query = 'INSERT INTO hr.employees_python (EMPLOYEE_ID, NAME, EMAIL, ' \
'PHONE_NUMBER, HIRE_DATE, JOB_ID, SALARY, MONTH, ' \
'DAY, YEAR) values (:0, :1, :2, :3, :4, :5, :6, :7, :8, :9)'
# you might not want to call oracle_con everytime.
oracle_conn()
self.con.executemany(query, values)
# a is not a very good name
a = Transformation()
# you can also access them here doing
# a.con
# a.cur
uj5u.com熱心網友回復:
你可以簡單地寫
n,m = oracle_conn()
或者,您可以以串列格式回傳它們,然后通過索引訪問它們。所以在 oracle_conn 中:
return [cur, con]
以及您想在哪里使用它:
stuff = oracle_conn()
n = stuff[0]
m = stuff[1]
編輯:但是,如果您只想在另一個功能中訪問它,這是一種方式。否則,我會建議與 Sembei Norimaki 相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/508621.html
上一篇:OracleDb中的未知資料庫函式“DATE_FORMAT”
下一篇:SQL中行圖之間的依賴關系
