使用python类控制mysql时出错
我正在尝试使用类系统更新mysql数据库,但无法使更新部分正常工作。这一切都是旧的方式,但我想使用异常错误控制类系统。有人能告诉我我做错了什么吗。目前,对于这个脚本,我只是尝试将变量Boileron发送到数据库列office使用python类控制mysql时出错,python,mysql,Python,Mysql,我正在尝试使用类系统更新mysql数据库,但无法使更新部分正常工作。这一切都是旧的方式,但我想使用异常错误控制类系统。有人能告诉我我做错了什么吗。目前,对于这个脚本,我只是尝试将变量Boileron发送到数据库列office import MySQLdb class DBSolar: conn = None def connect(self): try: self.conn = MySQLdb.connect("192.xxx.x.x"
import MySQLdb
class DBSolar:
conn = None
def connect(self):
try:
self.conn = MySQLdb.connect("192.xxx.x.x", "exxxxx", "Oxxxx", "hxxxx")
except (MySQLdb.Error, MySQLdb.Warning) as e:
print (e)
self.conn = None
return self.conn
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
def update(self, task):
boilerState = task
try:
sql = "UPDATE dashboard SET office = ? WHERE id = 1", (boilerState)
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return
while 1:
BoilerOn = 1
print BoilerOn
dbSolar = DBSolar()
connSolar = dbSolar.connect()
if connSolar:
dbSolar.update(BoilerOn)
下面是putty控制台的错误报告
Traceback (most recent call last):
File "test2.py", line 47, in <module>
dbSolar.update(BoilerOn)
File "test2.py", line 29, in update
cursor.execute(sql)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 223, in execute
self.errorhandler(self, TypeError, m)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorvalue
TypeError: query() argument 1 must be string or read-only buffer, not tuple
回溯(最近一次呼叫最后一次):
文件“test2.py”,第47行,在
dbSolar.update(BoilerOn)
更新中第29行的文件“test2.py”
cursor.execute(sql)
文件“/usr/lib/python2.7/dist packages/MySQLdb/cursors.py”,执行中的第223行
errorhandler(self,TypeError,m)
文件“/usr/lib/python2.7/dist packages/MySQLdb/connections.py”,第36行,在defaulterrorhandler中
提高错误值
TypeError:query()参数1必须是字符串或只读缓冲区,而不是元组
中的
由于默认情况下Connector/Python会关闭自动提交,MySQL 5.5及更高版本默认使用事务性InnoDB表,因此有必要使用connection的commit()方法提交更改。还可以使用rollback()方法回滚
您需要在cursor.execute(sql)之后添加self.conn.commit()
,以提交所有更改
或者打开
自动提交
,这在sql
中有描述,但创建一个元组,但是光标。execute(语句,参数)
需要一个字符串作为语句
的一个元组或一个字典作为参数
对于MySQL更新,您还需要提交执行
因此,请尝试:
self.conn.cursor.execute("UPDATE dashboard SET office = %s WHERE id = 1", (str(task), ))
self.conn.commit()
我建议您阅读关于在python中使用MySQL的更好的理解。得到了这项工作,并将更新更改为以下内容
def update(self, task):
try:
cursor = self.conn.cursor()
cursor.execute("UPDATE dashboard SET office = %s WHERE id = 1", [task])
self.conn.commit()
except (MySQLdb.Error, MySQLdb.Warning) as e:
print (e)
self.connect()
#cursor = self.conn.cursor()
#cursor.execute(sql)
#self.connect.commit()
return
我想您的意思是像我尝试过的cursor.execute(sql)self.conn.commit()一样,但仍然出现了一个错误。我将用错误更新我的原始帖子这已经停止了元组错误,但它没有更新数据库中的office行。我必须对此做更多的研究,在MySQL上运行一个直接SQL,看看你是否有同样的问题