How to read Mysql data with Python?

Asked

Viewed 246 times

1

I’m running a registration and product sales system. I need to have access to registered units to check how many units still remain to be sold (with each sale I’m decreasing the remaining units).

I have a sales table that contains : id, description, price, sale, day, month, units and other entries that contain the same things.

I used that code:

        cursor = banco.cursor()
        mudar_estoque = f"SELECT id from cadastros where id = {id_produto_vendido}"
        cursor.execute(mudar_estoque)
        banco.commit()

I am using the Mysql library.

-- > I was able to execute the command, but how can I get the data obtained through this execution in a variable?

2 answers

4


The method you’re looking for is the fetchall()

rows = cursor.fetchall()

UPDATE: rows will be as a list, which can be iterated as below

for row in rows:
        print(row["CAMPO_AQUI"])   # Também pode usar o índice: row[0]

Note: for the command SELECT there is no need for the banco.commit(). This will only be necessary for the INSERT, UPDATE or DELETE

See the fecthall with more details on documentation

I hope I’ve helped.

1

As Paul said, you will use the function rows = cursor.fetchall(), and from there just sweep the array rows as follows:

for row in rows:
        print(row["id"])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.