因此,MainApp.py中的一些代碼就像這樣,我關心的是DBQuery發生的位置。 DB302.py與MainApp.py位於同一文件夾中,幷包含一個名爲DB302的類,其成員方法查詢如下所示。爲什麼只有當我使用DB302.DB302.query(DBQuery...)
時DBQuery
已經是DB302.DB302...
的實例有沒有辦法不必先使用,實例DBQuery = DB302.DB302()
而不是DBQuery = DB302
,也可以用它作爲`DBQuery.query(Instance ,var1,var2)。成員方法,模塊,類變量及其作用域......試圖弄清楚如何全部使用它們
我的第二個問題涉及在DB302.py中使用self.method or variable
。我是否正確使用它們?我現在得到ThrowsU()
,並且無法弄清楚原因。我的數據庫已被設置爲正常工作,我可以通過python終端訪問它。 Id是主鍵,我正在爲每個測試用例增加它。
#MainApp.py
import DB302
class MainApp(object):
@cherrypy.expose
def default(self, *args, **kwargs):
page = "<b>"args" has %d variables</b><br/>\n" % len(args)
for x in xrange(0, len(args)):
if args[x] == "":
page += "<i>error</i>\n"
else:
page += args[x] + "<br/>\n"
page += "<b>"cherrypy.request.params" has %d variablez</b><br/>\n" % len(cherrypy.request.params)
for key, value in cherrypy.request.params.items():
if cherrypy.request.params[key] == "":
page += "<i>empty</i>\n"
elif key == "username":
DBQuery = DB302.DB302()
data = DB302.DB302.query(DBQuery, 'SELECT * FROM test', 'SELECT')
else:
page += key + " = " + value + "<br/>\n"
page += """
<form name="form1" method="POST" action="/testURL/part2">
<input name="username" type="text" maxlength="256" autocomplete="off">
</input>
</form>
"""
return page
#DB302.py
import sqlite3
class DB302(object):
def __init__(self):
print "<b>Within DB302</b><br/>\n"
def throws(self):
raise RuntimeError('Connection to DB failed, terminating...')
def throwsQ(self):
raise RuntimeError('Error in DB query, terminating...')
def throwsU(self):
raise RuntimeError('Unknown DB error encountered...')
def connect(self):
# Where the DB connection will be made
CS302="<!-- Private -->" # The datbase file is on my desktop
try:
DBCon=sqlite3.connect(CS302)
cursor=DBCon.cursor()
return True
except IOError:
self.throws()
except:
self.throwsU()
else:
return False
def disconnect(self):
# Used to disconnect...
try:
self.cursor.close()
return True
except IOError:
self.throws()
except:
self.throwsU()
else:
return False
def query(self, queryString, queryType):
# Queries will be made here
if self.connect():
try:
self.cursor.execute(queryString)
if queryType == "SELECT":
# return all the rows if there's a select query
allRows = self.cursor.fetchall()
return allRows
elif queryType == "DELETE":
# return affected rows if there's a deletion
rowsAffected = self.cursor.rowcount()
self.DBCon.commit()
return rowsAffected
elif queryType == "INSERT":
# return true if success
self.DBCon.commit()
return True
elif queryType == "CREATE":
self.DBCon.commit()
return True
else:
return False
except IOError:
self.throwsQ()
except:
self.throwsU()
else:
return False
好吧出於某種原因使用預期的實例化'的DBQuery = DB302.DB302()''然後DBQuery.query(ARG1,Arg2)將'現在的作品。無論如何減少它到DB302()的任何方式?靜態從查詢方法中獲取'throwsU()'(此複製粘貼從底部開始的第3行) – Supernovah 2012-03-21 02:20:09