table
中的我的kwarg **kwarg
在我调用时无法识别。
class Database():
def set_db_setting(self, host, username, passwd, database):
try:
self.host = host
self.username = username
self.passwd = passwd
self.database = database
self.db = pymysql.connect(host=host, user=username, passwd=passwd, db=database)
print('connected to: {}'.format(database))
return self.db
except:
print('\nerror connecting to database\n')
def db_select(self, *selected_fields, **kwargs):
self.selected_fields = selected_fields = list(selected_fields)
self.table = (kwargs['table']
if 'table' in kwargs
else selected_fields.pop())
try:
with self.db.cursor() as cursor:
sql_tld_id_query = Database.query_stmt_list[0]+ ', '.join(selected_fields) + Database.query_stmt_list[4] + table + Database.query_stmt_list[5] + where_field + '=' + 'www.website.com'
print("sql_tld_id_query is {}".format(sql_tld_id_query))
except Exception as gatherid_err:
print("exception was {}".format(gatherid_err))
self.db.rollback()
I'm invoking it like:
dbclass = Database()
dbclass.set_db_setting('localhost', 'root', 'password', 'garbagedb')
dbclass.db_select('id', 'name', table='tld', where_field='name')
我收到的错误如下:
名称'table'未定义
完全跟踪 通过以下方式调用:
import traceback
traceback.print_stack()
`
File "dbcrud.py", line 56, in <module>
dbclass.db_select('id', 'name', table='tld', where_field='name')
File "dbcrud.py", line 31, in db_select
traceback.print_stack()
self.selected_fields is ['id', 'name']
exception was name 'table' is not defined
我在这里做错了什么?
答案 0 :(得分:0)
我添加了线条延续以使其适合水平...
sql_tld_id_query = Database.query_stmt_list[0]+ ', '.join(selected_fields) + \
Database.query_stmt_list[4] + table + Database.query_stmt_list[5] + \
where_field + '=' + 'www.website.com'
粗体的table
应为self.table
你盲目地抓住了try
except Exception
阻止所有异常,这可能隐藏了你的真实问题。最好找出你想要捕获的特定类型的异常,并且只过滤掉那些异常。例如,如果我想让一个计算器程序在用户试图除以零时没有崩溃,我会使用try: ... except ZeroDivisionError as e: ...