-2
我已經查看了Stackoverflow上的錯誤,但是我沒有看到任何解決方案可以解決我的問題。我正在嘗試爲cx_Oracle創建一個類,以將我的數據庫連接置於類中,並在我的數據庫實例中調用它。 我在C#中創建了類似的類,但由於某種原因python特別困難。任何援助讚賞。調用類,獲取TypeError:必須調用未綁定的方法
我槓桿這裏找到這段代碼: cx_Oracle and Exception Handling - Good practices?
import sys
import os
import cx_Oracle
class Oracle(object):
__db_server = os.getenv("ORACLE_SERVER")
__db_user = os.getenv("ORACLE_ACCT")
__db_password = os.getenv("ORACLE_PWD")
def connect(self):
""" Connect to the database. """
try:
self.db = cx_Oracle.connect(__db_user+'/'+__db_password+'@'+__db_server)
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 1017:
print('Please check your credentials.')
else:
print('Database connection error: %s'.format(e))
# Very important part!
raise
# If the database connection succeeded create the cursor
# we-re going to use.
self.cursor = db.Cursor()
def disconnect(self):
"""
Disconnect from the database. If this fails, for instance
if the connection instance doesn't exist we don't really care.
"""
try:
self.cursor.close()
self.db.close()
except cx_Oracle.DatabaseError:
pass
def execute(self, sql, bindvars=None, commit=False):
"""
Execute whatever SQL statements are passed to the method;
commit if specified. Do not specify fetchall() in here as
the SQL statement may not be a select.
bindvars is a dictionary of variables you pass to execute.
"""
try:
self.cursor.execute(sql, bindvars)
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 955:
print('Table already exists')
elif error.code == 1031:
print("Insufficient privileges")
print(error.code)
print(error.message)
print(error.context)
# Raise the exception.
raise
# Only commit if it-s necessary.
if commit:
self.db.commit()
def select(self, sql, commit=False):
bindvars=None
result = None
try:
self.cursor.execute(sql, bindvars)
result = self.cursor.fetchall()
except cx_Oracle.DatabaseError as e:
error, = e.args
print "Database Error: failed with error code:%d - %s" % (error.code, error.message)
raise
if commit:
self.db.commit()
return result
def commit(self):
try:
self.db.commit()
except cx_Oracle.DatabaseError as e:
error, = e.args
print "Database Commit failed with error code:%d - %s" % (error.code, error.message)
raise
def rollback(self):
try:
self.db.rollback()
except cx_Oracle.DatabaseError as e:
error, = e.args
print "Database Rollback failed with error code:%d - %s" %(error.code, error.message)
raise
這是我的調用程序
import sys
import os
#import cx_Oracle
from Oracle import Oracle
def main():
oracle = Oracle.connect()
query = """SELECT DISTINCT NAME FROM MyTable"""
data = oracle.select(query)
for row in data:
print row
oracle.disconnect()
### MAIN
if __name__ == '__main__':
main()
相關提示:我似乎無法讓Python找到我的Oracle .py類,除非它與調用函數位於同一目錄中。
艾倫
是你要實例化的類? –
(不是這樣)專家提示:通過Google搜索與錯誤相關的部分問題標題,我發現了StackOverflow上的鏈接副本。 –
是的,它似乎是我的問題中引用的示例,並且標記的副本不完整。因此導致另外的問題。 –