Search code examples
pythonmysqlpymysql

PyMySql cursor fetch all return empty when database has rows in python


Following is the code, i get the result as empty array but cursor has rows shows rowcount > 1 :

``

def __init__(self,readLink):
    if readLink==0:
        self.linksToRead = 1000000000
    else:
        self.linksToRead = readLink
    self.linkCount = 0
    self.wordsList =[]
    self.parsedLinks=[]
    self.urlList =[]
    self.connection = pymysql.connect(host='localhost',
                         user='root',
                         password='s3cr3tp@ssw0rd',
                         db='scrapper',
                         charset='utf8',
                         cursorclass=pymysql.cursors.DictCursor, autocommit=True)


    with self.connection.cursor() as cursor:

        sql2 = "SELECT * FROM `linksparsed`"
        try:
            cursor.execute(sql2)
            #self.connection.commit()
        except Exception as ex:
            print(ex)

        result = cursor.fetchall()
        cursor.rowcount  #shows 3
        totalLength = len(result) # shows 0
        for row in result:
            self.parsedLinks.append(row)

Solution

  • What is the rownumber after fetchall() ? if it is 3, equals to rowcount, means have already fetched rows.

    This is the source codes of fetchall, suppose return at "result self._rows[self.rownumber:]"

    def fetchall(self):
        """Fetch all the rows"""
        self._check_executed()
        if self._rows is None:
            return ()
        if self.rownumber:
            result = self._rows[self.rownumber:]  <<-------
        else:
            result = self._rows
        self.rownumber = len(self._rows)
        return result