关于python:毫无意义的-fetchonepymysql-中的-fetchone-有什么意义吗

7次阅读

共计 732 个字符,预计需要花费 2 分钟才能阅读完成。

毫无意义的 fetchone

import pymysql.cursors
from pymysql.connections import Connection
from pymysql.cursors import Cursor
import time

# Connect to the database
connection = pymysql.connect(host='192.168.31.203',
                             user='root',
                             password='yjcyjc',
                             database='d_replication_db')

with connection:
    connection: Connection

    with connection.cursor() as cursor:
        cursor:Cursor
        # Create a new record
        sql = "select * from master_slave_tweet;"
        cursor.execute(sql)
        for _ in range(10):
            print(cursor.fetchone())

  • fetchone 不是一次从 mysql server 中取一次,而是在你执行 cursor.execute(sql) 的时候就把所有的数据取回来了,所以每调用 fetchone 一次,就发动一个网络申请(基本不会发动网络申请)
  • fetchone 会节约网络申请工夫吗?不会,起因如上
  • fetchone 会节约内存空间吗?不会,起因如上
  • fetchone 的意义是什么呢?毫无意义,他也不能帮咱们写出更优雅的办法。

比如说你想获取某个表的第一条数据,必须应用 select * from master_slave_tweet limit 1; 而不是 select * from master_slave_tweet; 之后再应用 fetchone

正文完
 0