我不知道为什么我会遇到这个错误。请赐教。这是我的代码: filename:sqlfunc.py
from sqlalchemy import create_engine
class SQL:
def __init__(self):
self.connection_string = ''
self.sql = ''
def exec_nonquery(connection_string, sql):
self.connection_string = connection_string
self.sql = sql
self.__connection = self.__mydb(self.connection_string)
self.__transaction = self.__connection.begin()
try:
self.__connection.execute(self.sql).fetchall()
self.__transaction.commit()
except:
self.__transaction.rollback()
raise
_connection.close()
def exec_query(self, connection_string, sql):
self.connection_string = connection_string
self.sql = sql
self.__connection = self.__mydb(self.connection_string)
self.__result = None
self.query_result = []
try:
self.__result = self.__connection.execute(sql)
self.query_result = list(self.__result)
except:
raise
self.__connection.close()
return self.query_result
现在,我试过了:
from sqlfunc import SQL
SQL.exec_nonquery('mssql+pyodbc://scott:tiger@mydsn','select * from table1')
我收到了这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./sqlfunc.py", line 25, in exec_nonquery
self.connection_string = connection_string
NameError: global name 'self' is not defined
我做错了什么或丢失了吗?
我将exec_nonquery更改为
def exec_nonquery(self, connection_string, sql)
但它引发了我的错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exec_nonquery() missing 1 required positional argument: 'sql'
答案 0 :(得分:4)
“我做错了什么或丢失了什么?” - 是的,你没有将self
作为你方法的第一个位置参数:
def exec_nonquery(connection_string, sql):
应该是
def exec_nonquery(self, connection_string, sql):
# ^ see here
您还尝试在类上调用此实例方法。最小的修复是:
sql = SQL() # create instance
sql.exec_nonquery('mssql+pyodbc://scott:tiger@mydsn',
'select * from table1') # call method
但正如Martijn指出的那样,你真的应该重构这个课程以充分利用OOP。