mysql打开游标失败_Python:MySQL连接已打开,但无法创建游标

bd96500e110b49cbb3cd949968f18be7.png

I'm trying to open a cursor to a MySQL-DB. But I'm getting this error:

'NoneType' object has no attribute 'cursor'

Here is a small sourcecode:

class Sample:

def __init__(self):

self.conn = None

self.value = self.setValue()

def connect(self):

self.conn = MySQLdb.connect(...)

#cursor = self.conn.cursor()

#cursor.execute("SELECT ...")

#value = str(cursor.fetchone()[0])

#raise Exception(value)

#cursor.close()

def setValue(self):

if (self.conn == None):

self.connect()

#raise Exception(self.conn.open)

cursor = self.conn.cursor() # ERROR: 'NoneType' object has no attribute 'cursor'

...

If I use the exception I get a 1 ... connection is open.

And if I do the cursor creation and the SQL statement in the 'connect' function everything is working well.

The strange this is, everything looks correct and for some other connections with the same functions everything is working well, too. I don't know how to solve this error. I hope someone can point me in the right direction.

解决方案

I would change the statement that checks if the connection is open to both check if conn is none as well as if the connection is open. And because you always execute the setValue function I would recommend that you call the connect inside the__init__ function.

class Sample:

conn = None

def __init__(self):

self.connect()

self.value = self.setValue()

self.close()

def connect(self):

self.conn = MySQLdb.connect(...)

def close(self):

if self.conn:

self.conn.close()

def setValue(self):

if not self.conn and not self.conn.open:

self.connect()

cursor = self.conn.cursor()

Also, remember that with the Python MySQL Connector you need to call commit after you execute a insert or update statement.

cur = self.conn.cursor()

cur.execute("...")

self.conn.commit()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值