为什么要使用mode='absolute'使索引回到最初的位置

【问题】:为什么第二步要使用mode='absolute'使索引回到最初的位置呢?

self.cur.execute(condition)
self.cur.scroll(0,mode='absolute')# 游标索引回到初始位置
results =self.cur.fetchall()#返回游标中所有结果

【我的理解】:第二步是将游标回到原点,继而获取所有数据

1、我的数据库表数据是3条:

2、第一步是在游标下执行sql,那么执行的结果是先放在游标中的,这个没有异议;
3、第二步是在游标下执行.scroll方法,那么不清楚这一步具体是做啥的,我们看下Python源码是怎么解释的:

4、第三步在游标下执行fetchall()方法,同样我们看下Python源码是怎么解释的:

【更进一步】:设置游标位置

可以通过cursor.scroll(position, mode="relative | absolute")方法,来设置相对位置游标和绝对位置游标。
方法参数描述:
position : 游标位置(游标位置从0开始)
mode : 游标位置的模式(relative:默认模式,相对当前位置(即执行scroll方法时游标的位置);absolute:绝对位置)
例如:
mode=relative, position=1;表示的是设置游标为当前位置+1的位置,即向下移动一个位置
mode=absolute, position=2;将游标移动到索引为2的位置,无论当前位置在哪里

【样例解释】

#hrwang
#coding:utf-8
import MySQLdb
connection = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db='test_interface', charset='utf8')
cursor = connection.cursor()
# 返回执行结果数
nums = cursor.execute("select * from test_xml")#self._rows=<type 'tuple'>: ((1L, u'test1'), (2L, u'weqwe'), (3L, u'weqw'))
print(nums)#执行结果影响的数据条数
'''
    fetchone()源码
    def fetchone(self):
        """Fetches a single row from the cursor. None indicates that
        no more rows are available."""
        self._check_executed()
        if self.rownumber >= len(self._rows): return None
        result = self._rows[self.rownumber]
        self.rownumber = self.rownumber+1
        return result
'''
print(cursor.fetchone())  # 执行后,游标移动到索引位置为1,即self.rownumber=1
cursor.scroll(1,mode='relative')  # 相对游标移动模式,当前索引+1,即游标位置为2
'''
    fetchall()源码
    def fetchall(self):
        """Fetchs all available rows from the cursor."""
        self._check_executed()
        if self.rownumber:
            result = self._rows[self.rownumber:]
        else:
            result = self._rows
        self.rownumber = len(self._rows)
        return result
'''
print(cursor.fetchall())  # 因此获取所有数据即result=self._rows[2:],即result等于数据库第三个数
'''
    fetchmany()源码
    def fetchmany(self, size=None):
        """Fetch up to size rows from the cursor. Result set may be smaller
        than size. If size is not defined, cursor.arraysize is used."""
        self._check_executed()
        end = self.rownumber + (size or self.arraysize)
        result = self._rows[self.rownumber:end]
        self.rownumber = min(end, len(self._rows))
        return result
'''
print(cursor.fetchmany(size=1))  # 执行该语句前,self.rownumber=3,故result=()
cursor.scroll(0, mode="absolute")  # 绝对索引模式,将游标重置为0
print(cursor.fetchall())  # 因此获取所有数据,执行开始的时候self.rownumber=0,故result=self._rows
#执行结果是:
3
(1L, u'test1')
((3L, u'weqw'),)
()
((1L, u'test1'), (2L, u'weqwe'), (3L, u'weqw'))

################################################
先说下更新的原因:
今天在查询数据库数据时(表中无数据),使用self.cur.scroll(0,mode='absolute')会提示“out of range”,细心的朋友看源码也知道原因了,但是我不能理解源码为什么要这么写,难道没有数据就不能使用这个方法了吗?最后我没有找到原因也没去修改源码,默默的加了条数据。


链接:https://www.jianshu.com/p/2b327f1ddba1

猜你喜欢

转载自blog.csdn.net/hellocsz/article/details/82861449