[英]Python MySQLdb execute return int
我正在为我的项目使用 python 3.5.2。 我通过pip为 Mysql 连接安装了MySQLdb
。
代码:
import MySQLdb
class DB:
def __init__(self):
self.con = MySQLdb.connect(host="127.0.0.1", user="*", passwd="*", db="*")
self.cur = self.con.cursor()
def query(self, q):
r = self.cur.execute(q)
return r
def test():
db = DB()
result = db.query('SELECT id, name FROM test')
return print(result)
def test1():
db = DB()
result = db.query('SELECT id, name FROM test').fetchall()
for res in result:
id, name = res
print(id, name)
test()
test1()
#test output >>> '3'
#test1 output >>> AttributeError: 'int' object has no attribute 'fetchall'
测试表:
id | name
1 | 'test'
2 | 'test2'
3 | 'test3'
cursor.execute() 将返回修改或检索的行数,就像在 PHP 中一样。 您是否尝试过像这样返回 fetchall() ?
def query(self, q):
r = self.cur.execute(q).fetchall()
return r
有关更多文档,请参见此处: https : //ianhowson.com/blog/a-quick-guide-to-using-mysql-in-python/
请阅读此链接: http://mysql-python.sourceforge.net/MySQLdb.html
此时您的查询已经执行,您需要获取结果。 您有两个选择:
r=db.store_result()
...或... r=db.use_result() 两种方法都返回一个结果对象。 有什么不同? store_result() 将整个结果集返回到
客户立即。 如果您的结果集非常大,这可能是一个问题。 解决此问题的一种方法是向查询添加 LIMIT 子句,以限制返回的行数。 另一种是使用use_result(),它将结果集保存在服务器中,并在您获取时逐行发送。 但是,这确实会占用服务器资源,并且会占用连接:在获取所有行之前,您不能再执行任何查询。 通常我建议使用 store_result() ,除非您的结果集非常大并且由于某种原因您不能使用 LIMIT 。
def test1():
db = DB()
db.query('SELECT id, name FROM test')
result = db.cur.fetchall()
for res in result:
id, name = res
print(id, name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.