2017-01-23 94 views
-2

我为我的项目使用python 3.5.2。我通过pip为Mysql连接安装了MySQLdbPython MySQLdb执行返回int

代码:

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' 

回答

0

请阅读此链接: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)