Python Mysql database connection

Asked

Viewed 1,609 times

0

Trying to make the connection to my database, but is returning me the following error!

Exception has occurred: Attributeerror 'Connection' Object has no attribute 'execute' Exception has occurred: Attributeerror 'Connection' Object has no attribute 'execute'

Just follow the code

import pymysql

connection = pymysql.connect(host="reveka", user="carga", passwd="carga", db="dw")

if connection:
    print ("Conectado!\n")

#Realizando select para testar conexão 
mysql = '''\
    SELECT * FROM ft_venda
'''
cursor = connection.execute(mysql)

for Tabela in cursor:
    print(Tabela)

2 answers

2

To begin with, you added the library pymysql, but is willing to use the pymysql.cursor. Do the right import:

import pymysql.cursor

Before calling cursor.execute() you have to set that will work with the variable cursoras connection.cursor(). Thus:

connection = pymysql.connect(host="reveka", user="carga", passwd="carga", db="dw")


try:    
    with connection.cursor() as cursor:
        mysql = 'SELECT * FROM ft_venda'
        cursor.execute(mysql)
        resultado = cursor.fetchall()
        print(resultado)
finally:
    connection.close()

Tip: na library documentation has an example of how to make the call properly and can even give you an idea of how to improve your code if you want to handle the response in case of error with the connection.

  • Thank you very much Rafael :)

1


Example using your code

You can do this way as described in documentation

import pymysql.cursors

connection = pymysql.connect(host='reveka',
                             user='carga',
                             password='carga',
                             db='dw')

try:
    with connection.cursor() as cursor:
        sql = "SELECT * FROM ft_venda"
        cursor.execute(sql)
        result = cursor.fetchall()
        print(result)
finally:
    connection.close()

Important changes

Like the Rafael Barros quoted, you need the cursor for this task

import pymysql.cursors

And to get all the records I used fetchall

result = cursor.fetchall()

Since the documentation example is only returned a record

  • 1

    Thank you Wictor You helped a lot here :)

Browser other questions tagged

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