Python MySQL – Consultar dados de uma tabela em Python

Resumo : Este tutorial mostra como consultar dados de um banco de dados MySQL em Python usando MySQL Connector/Python API, como fetchone(), fetchmany()e fetchall().

Este tutorial continua de onde parou a conexão com um banco de dados MySQL em Python .

Para consultar dados em um banco de dados MySQL do Python, você precisa seguir as seguintes etapas:

  • Primeiro, conecte-se ao banco de dados MySQL e você obterá um MySQLConnectionobjeto.
  • A seguir, crie um  MySQLCursorobjeto a partir do MySQLConnectionobjeto.
  • Em seguida, use o cursor para executar uma consulta chamando seu  execute()método.
  • Depois disso, use fetchone()o  método fetchmany()ou  fetchall()para buscar dados do conjunto de resultados.
  • Por fim, feche o cursor e também a conexão com o banco de dados chamando o  close()método dos objetos correspondentes.

Mostraremos como usar os métodos fetchone(), fetchmany()fetchall()com mais detalhes nas seções a seguir.

Consultando dados com o método fetchone()

fetchone()método retorna a próxima linha de um conjunto de resultados de consulta ou Nonecaso não haja mais nenhuma linha. Vamos dar uma olhada no seguinte código:

from mysql.connector import MySQLConnection, Error
from config import read_config

def query_with_fetchone(config):
    # Initialize variables for cursor and connection
    cursor = None
    conn = None

    try:
        # Establish a connection to the MySQL database using the provided configuration
        conn = MySQLConnection(**config)
        
        # Create a cursor to interact with the database
        cursor = conn.cursor()
        
        # Execute a SELECT query to retrieve all rows from the 'books' table
        cursor.execute("SELECT * FROM books")

        # Fetch the first row
        row = cursor.fetchone()

        # Loop through all rows and print them
        while row is not None:
            print(row)
            row = cursor.fetchone()

    except Error as e:
        # Print an error message if an error occurs during the execution of the query
        print(e)

    finally:
        # Close the cursor and connection in the 'finally' block to ensure it happens
        if cursor:
            cursor.close()
        if conn:
            conn.close()

if __name__ == '__main__':
    # Read the database configuration from the 'config' module
    config = read_config()
    
    # Call the function with the obtained configuration to execute the query
    query_with_fetchone(config)
Linguagem de código:  Python  ( python )

Como funciona:

  • Primeiro, conecte-se ao banco de dados criando um novo  MySQLConnectionobjeto
  • A seguir, instancie um novo  MySQLCursorobjeto a partir do  MySQLConnectionobjeto
  • Em seguida, execute uma consulta que selecione todas as linhas da bookstabela.
  • Depois disso, busque a próxima linha no conjunto de resultados chamando o método fetchone(). No  whilebloco de loop, exiba o conteúdo da linha e passe para a próxima linha até que todas as linhas sejam buscadas.
  • Finalmente, feche o cursor e os objetos de conexão invocando o  close()método do objeto correspondente.

Observe que usamos a função read_config()do config.pymódulo criado no tutorial de conexão ao banco de dados MySQL .

Consultando dados com o método fetchall()

Se o número de linhas na tabela for relativamente pequeno, você poderá usar o  fetchall()método para buscar todas as linhas da tabela. Por exemplo:

from mysql.connector import MySQLConnection, Error
from config import read_config

def query_with_fetchall(config):
    try:
        # Establish a connection to the MySQL database using the provided configuration
        conn = MySQLConnection(**config)
        
        # Create a cursor to interact with the database
        cursor = conn.cursor()
        
        # Execute a SELECT query to retrieve all rows from the 'books' table
        cursor.execute("SELECT * FROM books")
        
        # Fetch all rows from the result set
        rows = cursor.fetchall()

        # Print the total number of rows returned by the query
        print('Total Row(s):', cursor.rowcount)
        
        # Loop through all rows and print them
        for row in rows:
            print(row)

    except Error as e:
        # Print an error message if an error occurs during the execution of the query
        print(e)

    finally:
        # Close the cursor and connection in the 'finally' block to ensure it happens
        cursor.close()
        conn.close()

if __name__ == '__main__':
    # Read the database configuration from the 'config' module
    config = read_config()
    
    # Call the function with the obtained configuration to execute the query
    query_with_fetchall(config)
Linguagem de código:  Python  ( python )

A lógica é semelhante ao exemplo do  fetchone()método, exceto pela  fetchall()parte da chamada do método.

Como buscamos todas as linhas da bookstabela na memória, podemos obter o total de linhas retornadas usando a  rowcountpropriedade do objeto cursor.

Consultando dados com o método fetchmany()

Para uma tabela relativamente grande, buscar todas as linhas e retornar todo o conjunto de resultados pode ser demorado. Além disso, o fetchall()método requer a alocação de memória suficiente para armazenar o conjunto completo de resultados na memória, levantando questões de eficiência.

MySQL Connector/Python possui o  fetchmany()método que retorna o próximo número de linhas (n) do conjunto de resultados, o que permite equilibrar o tempo de recuperação e o espaço de memória.

Aqui está o programa que usa o fetchmany()método para buscar todas as linhas do conjunto de resultados da consulta:

from mysql.connector import MySQLConnection, Error
from config import read_config

def iter_row(cursor, size=10):
    # Infinite loop to fetch rows in chunks of 'size' from the result set
    while True:
        rows = cursor.fetchmany(size)
        # Break the loop if there are no more rows to fetch
        if not rows:
            break

        # Yield each row in the fetched chunk
        for row in rows:
            yield row

def query_with_fetchmany(config):
    # Initialize variables for connection and cursor
    conn = None
    cursor = None

    try:
        # Establish a connection to the MySQL database using the provided configuration
        conn = MySQLConnection(**config)
        
        # Create a cursor to interact with the database
        cursor = conn.cursor()

        # Execute a SELECT query to retrieve all rows from the 'books' table
        cursor.execute("SELECT * FROM books")

        # Iterate over rows using the custom iterator function 'iter_row'
        for row in iter_row(cursor, 10):
            print(row)

    except Error as e:
        # Print an error message if an error occurs during the execution of the query
        print(e)

    finally:
        # Close the cursor and connection in the 'finally' block to ensure it happens
        if cursor:
            cursor.close()
        
        if conn:
            conn.close()

if __name__ =='__main__' :
    # Read the database configuration from the 'config' module
    config = read_config()
    
    # Call the function with the obtained configuration to execute the query
    query_with_fetchmany(config)
Linguagem de código:  PHP  ( php )

Primeiro, defina um gerador que divida as chamadas do banco de dados em uma série de  fetchmany()chamadas:

def iter_row(cursor, size=10):
    # Infinite loop to fetch rows in chunks of 'size' from the result set
    while True:
        rows = cursor.fetchmany(size)
        # Break the loop if there are no more rows to fetch
        if not rows:
            break

        # Yield each row in the fetched chunk
        for row in rows:
            yield rowLinguagem de código:  Python  ( python )

Segundo, use o  iter_row()gerador para buscar 10 linhas por vez:

def query_with_fetchmany(config):
    # Initialize variables for connection and cursor
    conn = None
    cursor = None

    try:
        # Establish a connection to the MySQL database using the provided configuration
        conn = MySQLConnection(**config)
        
        # Create a cursor to interact with the database
        cursor = conn.cursor()

        # Execute a SELECT query to retrieve all rows from the 'books' table
        cursor.execute("SELECT * FROM books")

        # Iterate over rows using the custom iterator function 'iter_row'
        for row in iter_row(cursor, 10):
            print(row)

    except Error as e:
        # Print an error message if an error occurs during the execution of the query
        print(e)

    finally:
        # Close the cursor and connection in the 'finally' block to ensure it happens
        if cursor:
            cursor.close()
        
        if conn:
            conn.close()Linguagem de código:  Python  ( python )

Terceiro, chame a função query_with_fetchmany() com a configuração do banco de dados:

if __name__ =='__main__' :
    # Read the database configuration from the 'config' module
    config = read_config()
    
    # Call the function with the obtained configuration to execute the query
    query_with_fetchmany(config)Linguagem de código:  PHP  ( php )

Resumo

  • Use fetchone()o método para recuperar uma única linha de um conjunto de resultados.
  • Use fetchmany()o método para recuperar um número especificado de linhas de um conjunto de resultados.
  • Use fetchall()o método para recuperar todas as linhas de um conjunto de resultados.

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *