2017-01-23 4 views
-2

私のプロジェクトにはPython 3.5.2が使用されています。私はをpipでインストールしました。Python MySQLdb execute return 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():2つのオプションがあります。違いは何ですか? store_result()は、クライアント全体を

に設定した結果全体を返します。結果セットが本当に大きい場合は、 が問題になります。これを回避する方法の1つは、返される行数を制限するために、クエリの にLIMIT句を追加することです。もう1つは 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) 
0

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/